简体   繁体   中英

Count nested json objects from a nested array in python

I have a JSON file thats goes that way :

在此处输入图片说明

As you can see, for the category Chemistry, theres two blocks. In this JSON file, theres different categories, and I would like to count how many times there is "id's" inside a each category.

So for this example, I would like to have the sum of blocks found under "Chemistry".

This is what I did , but I received "TypeError:String indices must be integers"

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)

EDIT:

here is the JSON link: http://api.nobelprize.org/v1/prize.json

And here the JSON viewer since it's very messy: http://jsonviewer.stack.hu/

Try this ?

sum([len(item["laureates"]) for item in nobel["prizes"] if item["category"] is 'chemistry' and "laureates" in item])

nobel is basically the data you've read.

first, you must known the structure of this json: this json is an Object with a key "prizes",then the key "prizes" is an array, so if you want to get the content what you want,you must get the array from the "prizes" key

whatYouWillGet = [item for item in nobel]
print(whatYouWillGet)
// it will print ["prizes"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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