Skip to content

Instantly share code, notes, and snippets.

@amirziai
Last active December 8, 2022 18:09
Show Gist options
  • Save amirziai/2808d06f59a38138fa2d to your computer and use it in GitHub Desktop.
Save amirziai/2808d06f59a38138fa2d to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@johnjbrusk
Copy link

This is very helpful. Can you help me think about how to reverse this using the output of the function... so taking the column naming pattern and serializing back to JSON in the same structure it was flattened from? Thanks again!

@ahim92
Copy link

ahim92 commented Jun 7, 2019

Thank you, have been struggling before I came across this piece of code!

@peopzen
Copy link

peopzen commented Aug 4, 2019

This is a useful tool. Any sample to fold this flatten json? I mean revert dict to json.

@Deepscodes
Copy link

@amirziai This is awesome, I was trying to flatten a multiple nested JSON object and this helped. Since it's recursive, the level of nesting is limited to how large the python stack is though?

@MatteyRitch
sample_object is interpreted as a tuple of two dictionaries since the two dicts are separated by a comma, but are not enclosed with anything. If you enclose with list brackets '[{dict_a} ,{ dict_b}]' then the flatten function should work and look like this:

{'1_Hobbies_0': 'Ultimate Frisbee', '1_Hobbies_1': 'Coding', '1_Location_City': 'New York', '0_Name': 'Chris', '0_Location_City': 'Los Angeles', '0_Hobbies_1': 'Polymorphing', '0_Hobbies_0': 'Ultimate Lawn Darts', '1_Location_State': 'NY', '0_Location_State': 'CA', '1_Name': 'Matthew'}

Not sure if that's the format you're looking for, but if you adjust the dict for example, add a row_0 and a row_1:
sample_object = {'row_0': {'Name':'Chris', 'Location':{'City':'Los Angeles','State':'CA'}, 'Hobbies':['Ultimate Lawn Darts', 'Polymorphing']}, 'row_1': {'Name':'Matthew', 'Location':{'City':'New York','State':'NY'},'Hobbies':['Ultimate Frisbee', 'Coding']}}

You then get something that looks a little more readable:
{'row_0_Hobbies_0': 'Ultimate Lawn Darts', 'row_0_Location_State': 'CA', 'row_0_Hobbies_1': 'Polymorphing', 'row_1_Location_City': 'New York', 'row_1_Name': 'Matthew', 'row_1_Hobbies_1': 'Coding', 'row_1_Hobbies_0': 'Ultimate Frisbee', 'row_1_Location_State': 'NY', 'row_0_Location_City': 'Los Angeles', 'row_0_Name': 'Chris'}

I am trying to create a table on top this data set, since everything is coming in one big row , Is there a create a table from this data set?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment