简体   繁体   中英

How to extract these data items from JSON file?

I have a JSON file and I would like to get 'id' value and 'key' value for each champion:

Here example with 2 champions of my champion.json file, but if I have 100 champions how can I do that?

{
    "type": "champion",
    "format": "standAloneComplex",
    "version": "9.23.1",
    "data": {
        "Aatrox": {
            "version": "9.23.1",
            "id": "Aatrox",
            "key": "266",
            "name": "Aatrox",
            "title": "the Darkin Blade"
        },
        "Ahri": {
            "version": "9.23.1",
            "id": "Ahri",
            "key": "103",
            "name": "Ahri",
            "title": "the Nine-Tailed Fox"
        }
    }
}

My python file:

import json

all_data = open('champion.json',  encoding="utf8")
data_champ = json.load(all_data)

for element in data_champ['data']:
    print(data_champ[element]["key"])
    print(data_champ[element]['id'])

In the structure of the JSON data in your question, the value associated with the data key is a dictionary-of-dictionaries, so you would need to access the value of each one of them like this:

import json

with open('champion.json',  encoding="utf8") as all_data:
    data_champ = json.load(all_data)

for value in data_champ['data'].values():
    print(value["key"])
    print(value['id'])

Output:

266
Aatrox
103
Ahri

I also changed the file handling to ensure it gets closed properly by using a with statement.

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