Guest User

Untitled

a guest
Nov 14th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. def flatten_json(nested_json):
  2. """Flatten json file with nested keys into a single level.
  3.  
  4. Args:
  5. nested_json: A nested json file.
  6.  
  7. Returns:
  8. The flattened json file if successful, None otherwise.
  9. """
  10. out = {}
  11.  
  12. def flatten(x, name=''):
  13. if type(x) is dict:
  14. for a in x:
  15. flatten(x[a], name + a + '_')
  16. elif type(x) is list:
  17. i = 0
  18. for a in x:
  19. flatten(a, name + str(i) + '_')
  20. i += 1
  21. else:
  22. out[name[:-1]] = x
  23.  
  24. flatten(nested_json)
  25.  
  26. return out
Add Comment
Please, Sign In to add comment