Skip to content

Instantly share code, notes, and snippets.

@bhbmaster
Last active July 17, 2023 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhbmaster/b4c2566a3b24f750c631b8b7f71d78e3 to your computer and use it in GitHub Desktop.
Save bhbmaster/b4c2566a3b24f750c631b8b7f71d78e3 to your computer and use it in GitHub Desktop.
Full Path Json

Note this is fullpathjson2.py from my article http://www.infotinks.com/full-path-json/

To download:

wget https://gist.githubusercontent.com/bhbmaster/b4c2566a3b24f750c631b8b7f71d78e3/raw/fullpathjson.py -O fullpathjson.py

curl https://gist.githubusercontent.com/bhbmaster/b4c2566a3b24f750c631b8b7f71d78e3/raw/fullpathjson.py -o fullpathjson.py

To run (with python3)

python3 fullpathjson.py some.json

python3 fullpathjson.py some.json > some.txt

import json
import sys
# import pprint
def flatten_json(nested_json: dict, exclude: list=[], delim: str = "/") -> dict:
"""Flatten json object with nested keys into a single level.
Args:
nested_json {dict}: A nested json object.
exclude {list}: Keys to exclude from output.
delim {str}: path delimiter, default is "/"
Returns:
{dict}: The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x: dict, name: str='', exclude: list=[]):
if type(x) is dict:
for a in x:
if a not in exclude:
flatten(x[a], f"{name}{delim}{a}", exclude)
elif type(x) is list:
i = 0
for a in x:
flatten(a, f"{name}{delim}{i}", exclude)
i += 1
else:
out[name[1:]] = x
flatten(nested_json, exclude=exclude)
return out
if __name__ == "__main__":
filename = sys.argv[1]
file_content = open(filename,"r").read()
dict_content = json.loads(file_content)
flattened_dict = flatten_json(dict_content)
# pprint.pprint(flattened_dict)
for key, value in flattened_dict.items():
print(f'{key}: {value}')
import json
import sys
import pprint
def flatten_json(nested_json: dict, exclude: list=[], delim: str = "/") -> dict:
"""Flatten json object with nested keys into a single level.
Args:
nested_json {dict}: A nested json object.
exclude {list}: Keys to exclude from output.
delim {str}: path delimiter, default is "/"
Returns:
{dict}: The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x: dict, name: str='', exclude: list=[]):
if type(x) is dict:
for a in x:
if a not in exclude:
flatten(x[a], f"{name}{delim}{a}", exclude)
elif type(x) is list:
i = 0
for a in x:
flatten(a, f"{name}{delim}{i}", exclude)
i += 1
else:
out[name[1:]] = x
flatten(nested_json, exclude=exclude)
return out
if __name__ == "__main__":
filename = sys.argv[1]
file_content = open(filename,"r").read()
dict_content = json.loads(file_content)
flattened_dict = flatten_json(dict_content)
pprint.pprint(flattened_dict)
# for key, value in flattened_dict.items():
# print(f'{key}: {value}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment