社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python 3 json解析返回错误的特定键

maskeda • 5 年前 • 886 次点击  

我正在构建一个脚本来获取存储在json键下的值 ['records']['short_name'] . 这将返回我们的应用程序的短名称。

JSON修订示例:

{
  "totalRecords": 214575,
  "nextPageAvailable": true,
  "records": [
    {
      "_id": "xxxxxxxxxxxxxxxx",
      "sys_updated_on": "2019-07-18 14:30:52",
      "short_name": "Application Test"
    }
  ],
  "lastUpdated": "2019-11-08T18:43:42.000Z"
}

我的修订代码:

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']['short_name'][0])

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

我得到的结果是:

Traceback (most recent call last):
  File "query.py", line 23, in <module>
    print(app_json['records']['short_name'][0])
TypeError: list indices must be integers or slices, not str
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50748
 
886 次点击  
文章 [ 1 ]  |  最新文章 5 年前
luigibertaco
Reply   •   1 楼
luigibertaco    5 年前

错误的原因是您试图获取密钥 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', [])