Skip to content

Instantly share code, notes, and snippets.

@spareslant
Created January 9, 2017 13:50
Show Gist options
  • Save spareslant/d5bfb0086710916ccab65446e94adfa1 to your computer and use it in GitHub Desktop.
Save spareslant/d5bfb0086710916ccab65446e94adfa1 to your computer and use it in GitHub Desktop.
Creates Full paths from root node to leaf node in a JSON file
#! /usr/bin/env python
# This programm will create paths from root nodes to leafnodes along with values from any json file or structure.
import json
import pprint
json_data = open('sample_json_file.json', 'r').read()
json_dict = json.loads(json_data)
stack = []
final_dict = {}
def do_walk(datadict):
if isinstance(datadict, dict):
for key, value in datadict.items():
stack.append(key)
#print("/".join(stack))
if isinstance(value, dict) and len(value.keys()) == 0:
final_dict["/".join(stack)] = "EMPTY_DICT"
if isinstance(value, list) and len(value) == 0:
final_dict["/".join(stack)] = 'EMPTY_LIST'
if isinstance(value, dict):
do_walk(value)
if isinstance(value, list):
do_walk(value)
if isinstance(value, unicode):
final_dict["/".join(stack)] = value
stack.pop()
if isinstance(datadict, list):
n = 0
for key in datadict:
stack.append(str(n))
n = n + 1
if isinstance(key, dict):
do_walk(key)
if isinstance(key, list):
do_walk(key)
if isinstance(key, unicode):
final_dict["/".join(stack)] = key
stack.pop()
do_walk(json_dict)
pprint.pprint(final_dict)
@ans1genie
Copy link

Nice work.
Thanks for sharing.

@Devarsh-leo
Copy link

Thankyou for this :)

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