社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

luigibertaco

luigibertaco 最近创建的主题
luigibertaco 最近回复了
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', [])