Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get nested elements from a JSON Object?

JSON file I have has following data:

{
    "P1":{
        "L1":{
            "crn":"1"
        },
        "L2":{
            "crn":"100"
        }
        
    },
    "P2":{
        "L3":{
            "crn":"xx"
        },
        "L4":{
            "crn":"xxxx"
        }
    }
}

How do I get [L1,L2,L3,L4] efficiently?
I can load the data and loop over dict.values().

Is there any better, efficient way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a list comprehension to extract the room numbers, then use itertools.chain.from_iterable to flatten everything into a one-dimensional list:

import json
from itertools import chain

with open('input.json') as input_file:
    data = json.load(input_file)
    # Prints ['L1', 'L2', 'L3', 'L4']
    print(list(chain.from_iterable(value.keys() for value in data.values())))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading