Open fakechris opened 5 years ago
Any update ?
I think a better implementation is below:
@classmethod
def from_dict(cls, d):
"""
Load tree from exported JSON string.
:param json_str: json string that exported by to_json method
"""
def _iter(nodes, parent_id):
for k,v in nodes.items():
node_id = v.get('id', uuid.uuid4())
children = v.get('children', None)
data = v.get('data', None)
if children:
yield (k, node_id, data, parent_id)
for child in children:
#yield from _iter(child, k)
for i in _iter(child, node_id):
yield i
else:
yield (k, node_id, data, parent_id)
tree = cls()
for i in _iter(d, None):
tag = i[0]
node_id = i[1]
data = i[2]
parent = i[3]
if parent is not None:
parent = tree[parent]
tree.create_node(tag=tag, identifier=node_id, parent=parent, data=data)
return tree
This will ensure you will be able to recreate a tree if the only thing you are interested in is the tags (which may be duplicated). A good example would be a binary tree or boolean expression tree.
The only improvement would be how you would specify the class constructor in this classmethod.
once you have the from_dict method, you can implement from_json by just json.load(d) and calling from_dict.
Are there any updates on this, from_json seems to be failing even on simple trees.