-
-
Save ans1genie/d8f17db4b7699d698982335635d16eef to your computer and use it in GitHub Desktop.
Creates Full paths from root node to leaf node in a JSON file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment