The*_*Kid 5 python iteration dictionary
这是我的要求。
h="API-AUTHENTICATION:key:secret"
r=requests.get("https://URL", h)
Run Code Online (Sandbox Code Playgroud)
这是回应:
<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
}
]
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
a=json.loads(r.text)
print(a.keys())
print(a)
Run Code Online (Sandbox Code Playgroud)
我明白了:
dict_keys(['status', 'data'])
Run Code Online (Sandbox Code Playgroud)
如何将其解析为字典并迭代它。现在,当我迭代它时,我只到达状态和数据字段。我尝试像这样迭代它:
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)
Run Code Online (Sandbox Code Playgroud)
response.json()
如果响应包含有效的JSON,将为您提供 json。
您可以检查响应有效负载标头中的“内容类型”,以验证响应是否为 jsonresponse.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())
Run Code Online (Sandbox Code Playgroud)
您的响应是一个带有 2 个键的 json status
,data
您可以直接从 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())
Run Code Online (Sandbox Code Playgroud)