Py学习  »  luigibertaco  »  全部回复
回复总数  1
4 年前
回复了 luigibertaco 创建的主题 » python 3 json解析返回错误的特定键

错误的原因是您试图获取密钥 short_name 从返回的列表中 records .

你只需要改变:

print(app_json['records']['short_name'][0])

print(app_json['records'][0]['short_name'])

最终准则是:

import json
import requests

url = "https://url.com/api/v3/data"

app_query = {"widgetId":"Assets", "asset_type":"Application", "install_status":"Active"}

headers = {
    'authority': "url.com",
    'accept': "application/json, textplain, */*",
    'authorization': "Bearer key_redacted",
    'Host': "url",
    'Accept-Encoding': "gzip, deflate",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

app_data = requests.request("GET", url, headers=headers, params=app_query)

app_json = json.loads(app_data.text)

if app_data.status_code == 200:
    print(app_json['records'][0]['short_name'])

elif app_data.status_code == 404:
    print('404 - Not Found.')

请注意,有些事情是可以改进的,例如。

app_json = json.loads(app_data.text)

可替换为:

app_json = app_data.json()

另外,如果记录列表返回一个空的记录列表,它也会中断。

考虑使用 .get() 从“不安全”的指令中收集数据时。

即:

app_json.get('records')
# you could optionally set a default value
app_json.get('records', [])