Skip to content

Instantly share code, notes, and snippets.

@rainsunny
Created October 17, 2019 07:57
Show Gist options
  • Save rainsunny/f3f051b4e765a40e13b7fcf62003f2ca to your computer and use it in GitHub Desktop.
Save rainsunny/f3f051b4e765a40e13b7fcf62003f2ca to your computer and use it in GitHub Desktop.
# Used to flatten json object while using pandas
from pandas.io.json import json_normalize
def flatten_json(y):
out = {}
def __flatten(x, name=''):
if type(x) is dict:
for a in x:
__flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
__flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
__flatten(y)
return out
flat = flatten_json(sample_object)
json_normalize(flat)
# reference: https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment