简体   繁体   中英

seeking help regarding converting data from nested JSON to flat json in python

I am looking for converting a nested json into flat json using python. I have the data coming from an API response, the number of keys/columns can be upto 100, and the rows/overall count of elements can be 100k

[{"Name":"John", "Location":{"City":"Los Angeles","State":"CA"}},{"Name":"Sam", "Location":{"City":"Chicago","State":"IL"}}]

I did came across this ( Python flatten multilevel JSON ) but this flattens the whole JSON completely, as a result everything falls under one line which I am not looking for currently. I also thought of using this on one the data one array at a time in loop but that is causing a lot of load on the system

[{"Name":"John", "City":"Los Angeles","State":"CA"},{"Name":"Sam", "City":"Chicago","State":"IL"}]

Use unpacking with dict.pop :

[{**d.pop("Location"), **d} for d in l]

Output:

[{'City': 'Los Angeles', 'Name': 'John', 'State': 'CA'},
 {'City': 'Chicago', 'Name': 'Sam', 'State': 'IL'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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