caesar0301 / treelib

An efficient implementation of tree data structure in python 2/3.
http://treelib.readthedocs.io/en/latest/
Other
801 stars 185 forks source link

from_json method to load tree from json. #105

Open fakechris opened 5 years ago

devmaha commented 4 years ago

Are there any updates on this, from_json seems to be failing even on simple trees.

lironesamoun commented 2 years ago

Any update ?

gammadistribution commented 1 year ago

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.