【问题标题】:python 3 json parsing specific keys returning errorspython 3 json解析特定键返回错误
【发布时间】:2019-12-02 23:44:56
【问题描述】:

我正在构建一个脚本来提取存储在 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

【问题讨论】:

  • 你试过app_data.json()吗?另外,你回复的内容是什么?你能把它贴在这里作为例子吗?
  • 我的猜测是 app_json['records'] 返回的是一个列表而不是一个字典,但需要一个例子来确定。
  • 更新删除测试数据并添加 json 样本

标签: json python-3.x parsing


【解决方案1】:

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

你只需要改变:

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

【讨论】:

  • 感谢我还修复了它:``` for each in app_json['records']: print(each['short_name']) ```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-05-14
  • 2015-03-26
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多