From b57b944aad859425b4dc294e8715cbbf1f33db21 Mon Sep 17 00:00:00 2001 From: Song ChuanSheng Date: Fri, 11 Jan 2019 15:17:05 +0800 Subject: [PATCH] from_json method to load tree from json. --- treelib/tree.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/treelib/tree.py b/treelib/tree.py index 0c106d5..38ec92f 100644 --- a/treelib/tree.py +++ b/treelib/tree.py @@ -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) + 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.