繁体   English   中英

如何从现在是字典的 json 数据中提取特定值

[英]How to extract specific value from json data that is now a dictionary

我正在开发一种工具,可以从我的公司 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 一样访问它。

您应该使用developer['result'][0]['number'] 您的变量Developer是一个字典和您想要的键, result是 1 个元素的列表(如我们所见),因此您必须首先引用字典键( developer )然后是索引( 0或任何它是)然后是另一个字典的键number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM