简体   繁体   English

解析大型json文件并在python中检索值

[英]parsing a large json file and retrieving values in python

I have one large json file of the format - 我有一个格式较大的json文件-

{
    "x": "",
    "y": {
        "a": {
            "-3": {
                "id": -2,
                "rut": "abc",

            },
            "-1": {
                "id": -1,
                 "rut": "cdf",

             } 
        }
     }
}

Now I want to retrieve the values of id for all situations. 现在,我想检索所有情况下的id值。 For this I have the following code - 为此,我有以下代码-

import json
from pprint import pprint

with open('file.json') as data_file:
data = json.load(data_file)
data['y']['a'].value()['id']

Since I'm not too familiar with using json in python, I couldn't figure out what I was doing wrong. 由于我对在python中使用json不太熟悉,因此我无法弄清楚自己在做什么错。 I used .value() because the values -3 and -1 could be any number and are not known before hand. 我使用.value()是因为值-3-1可以是任何数字,并且事先未知。 The rest of the values are constant. 其余值是恒定的。

import json from pprint import pprint 从pprint导入json导入pprint

with open('file.json') as data_file:
    data = json.load(data_file)
    pprint([item['id'] for item in data['y']['a'].values()])

Is it what you are looking for? 是您要找的东西吗?

It is a bit unclear what your problem/error is, but my gess is that you want to simply iterate over all the available values to get your 'id' fields. 尚不清楚您的问题/错误是什么,但是我的想法是,您只想对所有可用值进行迭代以获取“ id”字段。 It would look something like that: 它看起来像这样:

for x in data['y']['a']:
    try:
        print(x['id'])
    except IndexError: #In case 'id' isn't present in that subtree
        pass

Did you mean to use values() ? 您是要使用values()吗?

However, to get the all 'id's: 但是,要获取所有“ id”:

sub_data = data['y']['a']
for i in sub_data:
    print(sub_data['id'])

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

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