如何在python中解析对象的JSON数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48189684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON Array of objects in python
提问by Arul
I received the following JSON
Array from the POST
response of an HTTP
request:
我JSON
从请求的POST
响应中收到以下数组HTTP
:
[{
"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>..]
Given that typeof(response)
gives me requests.models.Response
, how can I parse it in Python
?
鉴于这typeof(response)
给了我requests.models.Response
,我该如何解析它Python
?
回答by Jim Wright
Take a look at the json module. More specifically the 'Decoding JSON:' section.
看看json 模块。更具体地说是“解码 JSON:”部分。
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
回答by MITHU
You can try like below to get the values from json response:
您可以尝试像下面这样从 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": "[email protected]",
"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": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
输出:
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
回答by Buzz
回答by Abhishek Kaushik
use python 3 and import urlib
使用 python 3 并导入 urlib
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"])