这是我的请求。
h="API-AUTHENTICATION:key:secret"
r=requests.get("https://URL", h)
这是回应:
<Response [200]>
如果我打印请求的纯文本 (print(r.text))
我明白了:
{
"status": "OK",
"data": [
{
"sort": 1,
"parent_name": "Stocktake Demo",
"timetables": [
{
"active": 1,
"from_date": "Nov 01, 2019",
"timetable_data": {
"monday": [
{
"to": "23:59",
"from": "00:00"
}
],
"tuesday": [
{
"to": "23:59",
"from": "00:00"
}
],
"friday": [
{
"to": "23:59",
"from": "00:00"
}
],
"wednesday": [
{
"to": "23:59",
"from": "00:00"
}
],
"thursday": [
{
"to": "23:59",
"from": "00:00"
}
],
"sunday": [
{
"to": "23:59",
"from": "00:00"
}
],
"saturday": [
{
"to": "23:59",
"from": "00:00"
}
]
},
"type": 1,
"to_date": ""
}
],
"name": "Stocktake Food",
"parent_id": 137585,
"parent_sort": 73,
"image": null,
"id": 137586,
"description": null
},
{
"sort": 1,
"parent_name": "Main Category",
"timetables": [
{
"active": 1,
"from_date": "Nov 01, 2019",
"timetable_data": {
"monday": [
{
"to": "23:59",
"from": "00:00"
}
],
"tuesday": [
{
"to": "23:59",
"from": "00:00"
}
],
"friday": [
{
"to": "23:59",
"from": "00:00"
}
],
"wednesday": [
{
"to": "23:59",
"from": "00:00"
}
],
"thursday": [
{
"to": "23:59",
"from": "00:00"
}
],
"sunday": [
{
"to": "23:59",
"from": "00:00"
}
],
"saturday": [
{
"to": "23:59",
"from": "00:00"
}
]
},
"type": 1,
"to_date": ""
}
],
"name": "Main Subcategory",
"parent_id": 117042,
"parent_sort": 2,
"image": null,
"id": 117043,
"description": null
}
]
}
如果我这样做:
a=json.loads(r.text)
print(a.keys())
print(a)
我明白了:
dict_keys(['status', 'data'])
如何将其解析为字典并对其进行迭代。现在,当我迭代它时,我只会到达状态和数据字段。我尝试像这样迭代它:
def print_depth(a, start=0):
for key, value in a.items():
print(key, start + 1)
if isinstance(value, dict):
print_depth(value, start=start + 1)
print_depth(a)
最佳答案
response.json()
如果响应包含 valid JSON,将为您提供 json。
您可以使用 response.headers.get('Content-Type')
import requests
response = requests.get('https://api.github.com')
if response.status_code == 200 and 'application/json' in response.headers.get('Content-Type',''):
print(response.json())
您的响应是一个带有 2 个键 status
和 data
的 json,您可以直接从 json 访问它们并迭代 data
值是一个列表
h="API-AUTHENTICATION:key:secret"
r=requests.get("https://URL", h)
if r.json().get('status') == 'OK':
for item in r.json().get('data'):
print(item.items())
关于Python请求获取JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59261113/