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

Conversation

fakechris
Copy link

No description provided.

@fakechris fakechris requested a review from caesar0301 as a code owner January 11, 2019 07:26
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

@devmaha
Copy link

devmaha commented Jul 15, 2019

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

@lironesamoun
Copy link

Any update ?

@gammadistribution
Copy link

gammadistribution commented Dec 12, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants