-2

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"}]

1 Answers1

0

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'}]
Chris
  • 29,127
  • 3
  • 28
  • 51