/!\ WARNING the order in a dictionnary is not guaranteed see here
a = {
"seasons": "episodes",
"peka": {"lol": "wow", "kek": {"wtf": "is this"}},
"ololo": "wololo"
}
The object a is dictionnary the order of (key, value) is not guaranteed, that is to say random if you do print(a)
, you have :
{'ololo': 'wololo', 'peka': {'kek': {'wtf': 'is this'}, 'lol': 'wow'}, 'seasons': 'episodes'}
It is another order.
To keep the same order, copy/past this type in the file file.json
and user
OrderedDict.
file.json:
{
"seasons": "episodes",
"peka": {"lol": "wow", "kek": {"wtf": "is this"}},
"ololo": "wololo"
}
Here your solution:
import json
from collections import OrderedDict
from pprint import pprint
with open('file.json', 'r') as filename:
a = json.load(filename, object_pairs_hook=OrderedDict)
def build_item(_id, parent_id, value):
return {'ID': _id, 'Parent_ID': parent_id, 'Value': value}
def dfs(_id, root, tree):
_id += 1
flat_tree = [build_item(_id, None, root)]
stack = [(_id, tree)]
while len(stack) != 0:
parent_id, tree = stack.pop(0)
if isinstance(tree, dict):
for value in tree.keys():
_id += 1
flat_tree.append(build_item(_id, parent_id, value))
stack.append((_id, tree[value]))
else:
value = tree
_id += 1
flat_tree.append(build_item(_id, parent_id, value))
return _id, flat_tree
def convert_dict_to_flat_tree(d):
flat_trees = list()
_id = 0
for root, tree in d.items():
_id, flat_tree = dfs(_id, root, tree)
flat_trees.extend(flat_tree)
return flat_trees
flat_tree = convert_dict_to_flat_tree(a)
pprint(flat_tree)
Output:
[{'ID': 1, 'Parent_ID': None, 'Value': 'seasons'},
{'ID': 2, 'Parent_ID': 1, 'Value': 'episodes'},
{'ID': 3, 'Parent_ID': None, 'Value': 'peka'},
{'ID': 4, 'Parent_ID': 3, 'Value': 'lol'},
{'ID': 5, 'Parent_ID': 3, 'Value': 'kek'},
{'ID': 6, 'Parent_ID': 4, 'Value': 'wow'},
{'ID': 7, 'Parent_ID': 5, 'Value': 'wtf'},
{'ID': 8, 'Parent_ID': 7, 'Value': 'is this'},
{'ID': 9, 'Parent_ID': None, 'Value': 'ololo'},
{'ID': 10, 'Parent_ID': 9, 'Value': 'wololo'}]