如何在Python中解析JSON对象数组

10

我从 HTTP 请求的 POST 响应中收到了以下的 JSON 数组:

[{
    "username": "username_1",
    "first_name": "",
    "last_name": "",
    "roles": "system_admin system_user",
    "locale": "en",
    "delete_at": 0,
    "update_at": 1511335509393,
    "create_at": 1511335500662,
    "auth_service": "",
    "email": "userid_1@provider_1.com",
    "auth_data": "",
    "position": "",
    "nickname": "",
    "id": "short-string-of-random-characters-1"
}, {
  ...
}
<more such objects>..]

Python 中,如果 typeof(response) 返回的是 requests.models.Response,我该如何解析它?


你需要使用 json 模块。 - chepner
它是一个数组还是一个字符串? - Nandu Kalidindi
如果不是的话,那么它就是一个数组,这意味着它已经被解析为JSON,所以我不确定你在这种情况下在问什么。可能是使用Python将字符串转换为JSON的重复问题。 - Nick stands with Ukraine
1
在将你的代码片段发布到公共论坛之前,你可能想要屏蔽个人信息,例如电子邮件电话号码等。 - y2k-shubham
4个回答

23

查看json模块,具体来说是'Decoding JSON:'一节。

import json
import requests

response = requests.get()  # api call

users = json.loads(response.text)
for user in users:
    print(user['id'])

不需要导入json,只需使用简单的Python字典和for循环即可,无需加载到json中。 - prashant thakre
1
@prashantthakre,您如何在不先对字符串进行JSON解码的情况下循环遍历字典? - Jim Wright

5
您可以尝试以下方式从JSON响应中获取值:
import json

content=[{
    "username": "admin",
    "first_name": "",
    "last_name": "",
    "roles": "system_admin system_user",
    "locale": "en",
    "delete_at": 0,
    "update_at": 1511335509393,
    "create_at": 1511335500662,
    "auth_service": "",
    "email": "adminuser@cognizant.com",
    "auth_data": "",
    "position": "",
    "nickname": "",
    "id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
    "username": "chatops",
    "first_name": "",
    "last_name": "",
    "roles": "system_user",
    "locale": "en",
    "delete_at": 0,
    "update_at": 1511335743479,
    "create_at": 1511335743393,
    "auth_service": "",
    "email": "chatops@cognizant.com",
    "auth_data": "",
    "position": "",
    "nickname": "",
    "id": "akxdddp5p7fjirxq7whhntq1nr"
}]

for item in content:
    print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))

输出:

Name: admin
Email: adminuser@cognizant.com
ID: pbjds5wmsp8cxr993nmc6ozodh

Name: chatops
Email: chatops@cognizant.com
ID: akxdddp5p7fjirxq7whhntq1nr

1
请在翻译时考虑掩盖代码片段中的个人信息,例如电子邮件。有关更多详细信息,请参见问题的编辑历史记录 - y2k-shubham

0

使用Python 3并导入urllib

import urllib.request
import json
url = link of the server 
#Taking response and request  from url

r = urllib.request.urlopen(url)
#reading and decoding the data
data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))


for json_inner_array in data:
        for json_data in json_inner_array:
                    print("id: "+json_data["id"])

-2

看起来你需要的是json模块。使用它,你可以将一个字符串解析成JSON格式:

import json
output=json.loads(myJsonString)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接