How to parse JSON Array of objects in python

Aru*_*rul 4 python json

I received the following JSON Array from the POST response of an HTTP request:

[{
    "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>..]
Run Code Online (Sandbox Code Playgroud)

Given that typeof(response) gives me requests.models.Response, how can I parse it in Python?

Jim*_*ght 12

Take a look at the json module. More specifically the 'Decoding JSON:' section.

import json
import requests

response = requests.get()  # api call

users = json.loads(response.text)
for user in users:
    print(user['id'])
Run Code Online (Sandbox Code Playgroud)


MIT*_*THU 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']))
Run Code Online (Sandbox Code Playgroud)

输出:

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

Name: chatops
Email: chatops@cognizant.com
ID: akxdddp5p7fjirxq7whhntq1nr
Run Code Online (Sandbox Code Playgroud)

  • 请考虑在您的回答中**屏蔽个人信息**,例如来自*片段*的*电子邮件*。有关更多详细信息,请参阅问题的[编辑历史记录](https://stackoverflow.com/posts/48189684/revisions) (2认同)