Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions treelib/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,26 @@ def to_json(self, with_data=False, sort=True, reverse=False):
"""To format the tree in JSON format."""
return json.dumps(self.to_dict(with_data=with_data, sort=sort, reverse=reverse))

def from_json(self, json_str):
"""
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():
children = v.get('children', None)
data = v.get('data', None)
if children:
yield (k, data, parent_id)
for child in children:
yield from _iter(child, k)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Integration test failed, yield from ... syntax was introduced in python 3.3. To support 2.6 and 2.7 I'd suggest the following change:

Suggested change
yield from _iter(child, k)
for i in _iter(child, k):
yield i

else:
yield (k, data, parent_id)

for i in _iter(json.loads(json_str), None):
self.create_node(i[0], i[0], parent=i[2], data=i[1])

def to_graphviz(self, filename=None, shape='circle', graph='digraph'):
"""Exports the tree in the dot format of the graphviz software"""
nodes, connections = [], []
Expand Down