How to iterate through JSON to print in a formatted way
Question:
This is the JSON i have
"""
{ "A":1,
"B":[
{
"C":
{
"D": "0"
},
"E":
{
"F": "1",
"G": [
{
"H": {
"I": 12,
"J": 21
}
}
]
}
}
]
}
"""
I want to print the JSON in the following way more likely in a tree fashion
-----------------------------------------------------------------------
--------------------------EXPECTED OUTPUT!-----------------------------
-----------------------------------------------------------------------
{
'title': 'ROOT',
'key': '0',
'children': [
{
'title': 'A',
'key': 'A',
'children':[]
},
{
'title': 'B',
'key': 'B',
'children':[
{
'title': 'C',
'key': 'C',
'children':[
{
'title': 'D',
'key': 'D',
'children':[]
}
]
},
{
'title': 'E',
'key': 'E',
'children':[
{
'title': 'F',
'key': 'F',
'children':[]
},{
'title': 'G',
'key': 'G',
'children':[
{
'title': 'H',
'key': 'H',
'children':[
{
'title': 'I',
'key': 'I',
'children':[]
},
{
'title': 'J',
'key': 'J',
'children':[]
}
]
}
]
}
]
}
]
}
]
}
here is the reference to the above printing pattern link !
Here is the code i tried
import json
from pprint import pprint
json_data = json.loads("""
{ "A":1,
"B":[
{
"C":
{
"D": "0"
},
"E":
{
"F": "1",
"G": [
{
"H": {
"I": 12,
"J": 21
}
}
]
}
}
]
}
""")
__version__ = '1.0.0'
_branch_extend = '│ '
_branch_mid = '├─ '
_branch_last = '└─ '
_spacing = ' '
last_items = []
main_json_obj = {
'title': """ ROOT """, 'key': 'ROOT',
'children': []
}
def _getHierarchy(jsonData, name='', file=None, _prefix='', _last=True):
""" Recursively parse json data to print data types """
# Handle object datatype
if isinstance(jsonData, dict):
name = name
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
_prefix += _spacing if _last else _branch_extend
length = len(jsonData)
for i, key in enumerate(jsonData.keys()):
_last = i == (length - 1)
_getHierarchy(jsonData[key], '"' + key + '"', file, _prefix, _last)
# Handle array datatype
elif isinstance(jsonData, list):
# name += ' (array)'
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
_prefix += _spacing if _last else _branch_extend
_getHierarchy(jsonData[0], '', file, _prefix, _last=True)
else:
# Handle string datatype
if isinstance(jsonData, str):
name = name
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
# Handle number datatype
else:
name = name
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
def setSymbols(branch_extend='│ ', branch_mid='├─ ', branch_last='└─ '):
""" Override symbols for the tree structure """
global _branch_extend
global _branch_mid
global _branch_last
_branch_extend = branch_extend
_branch_mid = branch_mid
_branch_last = branch_last
print("-----------------------------------------------------------")
print("-------------------Hierarchy is shown below--------------- ")
print("-----------------------------------------------------------")
print(" ")
_getHierarchy(json_data)
print(" ")
print("-----------------------------------------------------------")
print("-------------------Hierarchy ENDS HERE !--------------- ")
print("-----------------------------------------------------------")
print(" ")
print(" ")
print("--------------------OUTPUT AT THE MOMENT !!!!!!-------------- ")
print(" ")
print(" ")
pprint(main_json_obj)
print(" ")
print(" ")
this is its output at the moment!
-----------------------------------------------------------
-------------------Hierarchy is shown below---------------
-----------------------------------------------------------
└─
├─ "A"
└─ "B"
└─
├─ "C"
│ └─ "D"
└─ "E"
├─ "F"
└─ "G"
└─
└─ "H"
├─ "I"
└─ "J"
-----------------------------------------------------------
-------------------Hierarchy ENDS HERE !---------------
-----------------------------------------------------------
--------------------OUTPUT AT THE MOMENT !!!!!!--------------
{'children': [{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"A"', 'title': '"A"'},
{'children': [], 'key': '"B"', 'title': '"B"'},
{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"C"', 'title': '"C"'},
{'children': [], 'key': '"D"', 'title': '"D"'},
{'children': [], 'key': '"E"', 'title': '"E"'},
{'children': [], 'key': '"F"', 'title': '"F"'},
{'children': [], 'key': '"G"', 'title': '"G"'},
{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"H"', 'title': '"H"'},
{'children': [], 'key': '"I"', 'title': '"I"'},
{'children': [], 'key': '"J"', 'title': '"J"'}],
'key': 'ROOT',
'title': ' ROOT '}
If you observer closely, The difference between the output i want and the output i got is that the child item are being printed separately as a dictionary. But, i want to include them inside the children list of the parent.
For example the key "A" doesn’t have any children. So, it should be printed as a separate dictionary and its working this way as of now. But if you look at the key "B" it has keys "C" and "E" as its children. so "E and C" should be included inside B’s Children. moreover the keys "E and C" have children themselves, for "C" the child "D" and for "E" the children are "F" and "G" so "F and G" should be included in the children list of "E" . "D" should be inside children list of "C".
any help would be really appreciated!
Thanks in advance.
Answers:
Simple recursion:
def tree(json_data):
def _tree(obj):
if isinstance(obj, dict):
return [{'title': k, 'key': k, 'children': _tree(v)}
for k, v in obj.items()]
elif isinstance(obj, list):
return [elem
for lst in map(_tree, obj)
for elem in lst]
else:
return []
return {'title': 'ROOT', 'key': '0', 'children': _tree(json_data)}
Test:
>>> json_data = json.loads("""{
... "A": 1,
... "B": [
... {
... "C": {
... "D": "0"
... },
... "E": {
... "F": "1",
... "G": [
... {
... "H": {
... "I": 12,
... "J": 21
... }
... }
... ]
... }
... }
... ]
... }""")
>>> pp(tree(json_data), width=1)
{'title': 'ROOT',
'key': '0',
'children': [{'title': 'A',
'key': 'A',
'children': []},
{'title': 'B',
'key': 'B',
'children': [{'title': 'C',
'key': 'C',
'children': [{'title': 'D',
'key': 'D',
'children': []}]},
{'title': 'E',
'key': 'E',
'children': [{'title': 'F',
'key': 'F',
'children': []},
{'title': 'G',
'key': 'G',
'children': [{'title': 'H',
'key': 'H',
'children': [{'title': 'I',
'key': 'I',
'children': []},
{'title': 'J',
'key': 'J',
'children': []}]}]}]}]}]}
This is the JSON i have
"""
{ "A":1,
"B":[
{
"C":
{
"D": "0"
},
"E":
{
"F": "1",
"G": [
{
"H": {
"I": 12,
"J": 21
}
}
]
}
}
]
}
"""
I want to print the JSON in the following way more likely in a tree fashion
-----------------------------------------------------------------------
--------------------------EXPECTED OUTPUT!-----------------------------
-----------------------------------------------------------------------
{
'title': 'ROOT',
'key': '0',
'children': [
{
'title': 'A',
'key': 'A',
'children':[]
},
{
'title': 'B',
'key': 'B',
'children':[
{
'title': 'C',
'key': 'C',
'children':[
{
'title': 'D',
'key': 'D',
'children':[]
}
]
},
{
'title': 'E',
'key': 'E',
'children':[
{
'title': 'F',
'key': 'F',
'children':[]
},{
'title': 'G',
'key': 'G',
'children':[
{
'title': 'H',
'key': 'H',
'children':[
{
'title': 'I',
'key': 'I',
'children':[]
},
{
'title': 'J',
'key': 'J',
'children':[]
}
]
}
]
}
]
}
]
}
]
}
here is the reference to the above printing pattern link !
Here is the code i tried
import json
from pprint import pprint
json_data = json.loads("""
{ "A":1,
"B":[
{
"C":
{
"D": "0"
},
"E":
{
"F": "1",
"G": [
{
"H": {
"I": 12,
"J": 21
}
}
]
}
}
]
}
""")
__version__ = '1.0.0'
_branch_extend = '│ '
_branch_mid = '├─ '
_branch_last = '└─ '
_spacing = ' '
last_items = []
main_json_obj = {
'title': """ ROOT """, 'key': 'ROOT',
'children': []
}
def _getHierarchy(jsonData, name='', file=None, _prefix='', _last=True):
""" Recursively parse json data to print data types """
# Handle object datatype
if isinstance(jsonData, dict):
name = name
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
_prefix += _spacing if _last else _branch_extend
length = len(jsonData)
for i, key in enumerate(jsonData.keys()):
_last = i == (length - 1)
_getHierarchy(jsonData[key], '"' + key + '"', file, _prefix, _last)
# Handle array datatype
elif isinstance(jsonData, list):
# name += ' (array)'
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
_prefix += _spacing if _last else _branch_extend
_getHierarchy(jsonData[0], '', file, _prefix, _last=True)
else:
# Handle string datatype
if isinstance(jsonData, str):
name = name
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
# Handle number datatype
else:
name = name
if _last:
last_items.append([{'title': name, 'key': name, 'children': []}])
main_json_obj['children'] += [{'title': name, 'key': name, 'children': []}]
print(_prefix, _branch_last if _last else _branch_mid,
name, sep="", file=file)
def setSymbols(branch_extend='│ ', branch_mid='├─ ', branch_last='└─ '):
""" Override symbols for the tree structure """
global _branch_extend
global _branch_mid
global _branch_last
_branch_extend = branch_extend
_branch_mid = branch_mid
_branch_last = branch_last
print("-----------------------------------------------------------")
print("-------------------Hierarchy is shown below--------------- ")
print("-----------------------------------------------------------")
print(" ")
_getHierarchy(json_data)
print(" ")
print("-----------------------------------------------------------")
print("-------------------Hierarchy ENDS HERE !--------------- ")
print("-----------------------------------------------------------")
print(" ")
print(" ")
print("--------------------OUTPUT AT THE MOMENT !!!!!!-------------- ")
print(" ")
print(" ")
pprint(main_json_obj)
print(" ")
print(" ")
this is its output at the moment!
-----------------------------------------------------------
-------------------Hierarchy is shown below---------------
-----------------------------------------------------------
└─
├─ "A"
└─ "B"
└─
├─ "C"
│ └─ "D"
└─ "E"
├─ "F"
└─ "G"
└─
└─ "H"
├─ "I"
└─ "J"
-----------------------------------------------------------
-------------------Hierarchy ENDS HERE !---------------
-----------------------------------------------------------
--------------------OUTPUT AT THE MOMENT !!!!!!--------------
{'children': [{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"A"', 'title': '"A"'},
{'children': [], 'key': '"B"', 'title': '"B"'},
{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"C"', 'title': '"C"'},
{'children': [], 'key': '"D"', 'title': '"D"'},
{'children': [], 'key': '"E"', 'title': '"E"'},
{'children': [], 'key': '"F"', 'title': '"F"'},
{'children': [], 'key': '"G"', 'title': '"G"'},
{'children': [], 'key': '', 'title': ''},
{'children': [], 'key': '"H"', 'title': '"H"'},
{'children': [], 'key': '"I"', 'title': '"I"'},
{'children': [], 'key': '"J"', 'title': '"J"'}],
'key': 'ROOT',
'title': ' ROOT '}
If you observer closely, The difference between the output i want and the output i got is that the child item are being printed separately as a dictionary. But, i want to include them inside the children list of the parent.
For example the key "A" doesn’t have any children. So, it should be printed as a separate dictionary and its working this way as of now. But if you look at the key "B" it has keys "C" and "E" as its children. so "E and C" should be included inside B’s Children. moreover the keys "E and C" have children themselves, for "C" the child "D" and for "E" the children are "F" and "G" so "F and G" should be included in the children list of "E" . "D" should be inside children list of "C".
any help would be really appreciated!
Thanks in advance.
Simple recursion:
def tree(json_data):
def _tree(obj):
if isinstance(obj, dict):
return [{'title': k, 'key': k, 'children': _tree(v)}
for k, v in obj.items()]
elif isinstance(obj, list):
return [elem
for lst in map(_tree, obj)
for elem in lst]
else:
return []
return {'title': 'ROOT', 'key': '0', 'children': _tree(json_data)}
Test:
>>> json_data = json.loads("""{
... "A": 1,
... "B": [
... {
... "C": {
... "D": "0"
... },
... "E": {
... "F": "1",
... "G": [
... {
... "H": {
... "I": 12,
... "J": 21
... }
... }
... ]
... }
... }
... ]
... }""")
>>> pp(tree(json_data), width=1)
{'title': 'ROOT',
'key': '0',
'children': [{'title': 'A',
'key': 'A',
'children': []},
{'title': 'B',
'key': 'B',
'children': [{'title': 'C',
'key': 'C',
'children': [{'title': 'D',
'key': 'D',
'children': []}]},
{'title': 'E',
'key': 'E',
'children': [{'title': 'F',
'key': 'F',
'children': []},
{'title': 'G',
'key': 'G',
'children': [{'title': 'H',
'key': 'H',
'children': [{'title': 'I',
'key': 'I',
'children': []},
{'title': 'J',
'key': 'J',
'children': []}]}]}]}]}]}