简体   繁体   English

如何从 JSON 文件中提取这些数据项?

[英]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:我有一个 JSON 文件,我想获取每个冠军的 'id' 值和 'key' 值:

Here example with 2 champions of my champion.json file, but if I have 100 champions how can I do that?这里以我的champion.json文件的 2 个冠军为例,但如果我有 100 个冠军,我该怎么做?

{
    "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:我的 python 文件:

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:在您的问题中 JSON 数据的结构中,与data键关联的值是一个字典字典,因此您需要像这样访问它们中的每一个的值:

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: Output:

266
Aatrox
103
Ahri

I also changed the file handling to ensure it gets closed properly by using a with statement.我还更改了文件处理以确保使用with语句正确关闭它。

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

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