'How to get nested elements from a JSON Object? [closed]
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?
Solution 1:[1]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | not_speshal |
