json - python 3 json解析特定键返回错误
问题描述
我正在构建一个脚本来提取存储在 json key 下的值['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
解决方案
错误的原因是您试图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()
从“不安全”的字典中收集数据时考虑使用。
IE:
app_json.get('records')
# you could optionally set a default value
app_json.get('records', [])
推荐阅读
- node.js - 将 expressjs 添加到自定义 reactjs 应用程序
- shell - 如何使用特定字符串从过去 10 分钟的日志文件中获取行
- algorithm - 修改后的皇后问题的布尔表达式
- go - 如何确保按通道生产和消费数据是安全的
- java - Kotlin 等价于 Java `? 扩展`
- r - 在数字和 NA 列表中获取元素权重
- cluster-analysis - 如何在 Sklearn 中使用带有混合(分类和数字)数据的 silhouette_score?
- asp.net-mvc - (MVC) 我的共享 _Layout 中有一个搜索栏。它适用于其他视图,但不适用于 _Layout
- php - return redirect('/') 和 Redirect::to('/')->send() 有什么区别?laravel 中的函数
- snowflake-cloud-data-platform - 用于雪花的 Kafka 连接器不断失败