python - 如何从现在是字典的json数据中提取特定值
问题描述
我正在开发一种工具,可以从我的公司 CRM 工具中下载未结案例列表。我有将它们拉下来并放入文件的代码。文件格式为:
{
"result": [
{
"active":"true",
"number":"case_123",
"state":"Open",
"customer":"",
"priority":"3 - Moderate",
"assigned_to":"me",
"product":"My Product",
"contact_time_zone":"",
"opened_at":"23/07/2020 11:10:08",
"closed_at":""
},
"<more cases>"
],
}
我想提取键“数字”的所有值。
当您输入帖子主题时,我尝试遵循给出的一些建议。这似乎很接近: 如何从 JSON 中提取特定数据?
但没有奏效。
这是代码:
import json
print("Started Reading JSON file")
with open("sn_data.json", "r", encoding='utf-8') as read_file:
print("Converting JSON encoded data into Python dictionary")
developer = json.load(read_file)
print(developer['result']['number'])
这会抛出: print(developer['result']['number']) TypeError: list indices must be integers or slices, not str
我已经确认我有一本使用 print(type(developer)) 的字典。
如果我注释掉上面的打印并使用:
for number in developer.items():
print(developer.items["number"])
我得到: print(developer.items["number"]) TypeError: 'builtin_function_or_method' object is not subscriptable
我查找错误并没有找到真正的答案。由于我不是全职的 Python 开发人员,所以只支持试图提供帮助的人。
解决方案
字典中“结果”键的值是一个列表,因此您不能使用 ['number'] 对其进行索引。'number' 是该列表中字典中的键。
结果: [{}。{}...]
所以你必须迭代它。该列表中的每个项目都是一个字典,因此您可以使用 ['result'] 对其进行迭代
for result in developer['result']:
print(result['number'])
在您的第二个代码块中,您将一个值存储在一个名为number的变量中,然后您使用一个字符串“number”来访问它。仅供参考,这不是一回事。尽管如此, dict.items() 将返回一个列表,您也不能像 dict 一样访问它。
推荐阅读
- python - 通过命令行处理多个文件
- android - Sqlite Query 在 android 中不会产生正确的结果
- dart - Dart 2 类的构造函数与其他语言的多态性非常相似
- android - Unity 第一个版本是 debug 并成功上传到 Play 商店。第二个版本给出了错误。为什么?
- sql - sql中的表分布和表分区有什么区别?
- facebook - 从 Facebook 的 Graph API 获取用户个人资料链接
- django - Nginx - Django - Gunicorn:大文件上传在 30 秒后停止
- javascript - 在 React/TypeScript/Webpack 中覆盖 JSON 文件
- c# - C# ASP.NET Kendo 单行上的多个编辑命令
- sql-server - 将多个管道分隔的列解析为行,同时保留适当的对齐方式和 ID