0

I have one large json file of the format -

{
    "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. 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. I used .value() because the values -3 and -1 could be any number and are not known before hand. The rest of the values are constant.

2
  • What error are you getting? Commented Sep 11, 2016 at 20:07
  • @Jezor I'm getting an error at .value() as it doesn't seem to be recognized. Not sure how to read values when you don't know a specific attribute name beforehand Commented Sep 11, 2016 at 20:11

3 Answers 3

2

import json from pprint import 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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, exactly what I wanted. Thanks!
1

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. 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

Comments

0

Did you mean to use values() ?

However, to get the all 'id's:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.