Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

from_json method to load tree from json. #105

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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 @@ -824,6 +824,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 update_node(self, nid, **attrs):
"""
Update node's attributes.
Expand Down