[英]Count nested json objects from a nested array in python
我有一个这样的 JSON 文件:
如您所见,对于化学类别,有两个块。 在这个 JSON 文件中,有不同的类别,我想计算每个类别中有多少个“id”。
所以对于这个例子,我想要在“化学”下找到块的总和。
这就是我所做的,但我收到“类型错误:字符串索引必须是整数”
import json
with open('prize.json') as jsonfile:
nobel=json.load(jsonfile)
prizes = nobel
count = sum([len(item['prizes']['chemistry']) for item in nobel])
print(count)
编辑:
这是 JSON 链接: http : //api.nobelprize.org/v1/prize.json
这里是 JSON 查看器,因为它非常混乱: http : //jsonviewer.stack.hu/
尝试这个 ?
sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] is 'chemistry' and "laureates" in item])
nobel
基本上是你读过的数据。
首先,你必须知道这个json的结构:这个json是一个带有键“prizes”的Object,然后键“prizes”是一个数组,所以如果你想得到你想要的内容,你必须得到这个数组从“奖品”键
whatYouWillGet = [item for item in nobel]
print(whatYouWillGet)
// it will print ["prizes"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.