Home > Mobile >  How to get nested elements from a JSON Object?
How to get nested elements from a JSON Object?

Time:02-23

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?

CodePudding user response:

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())))

CodePudding user response:

Another way using list comprehension and flattening in a single line (assuming your json is saved to a dictionary called buildings):

>>> [item for sublist in buildings.values() for item in sublist]
['L1', 'L2', 'L3', 'L4']
  • Related