Search code examples
pythonjsontree

How can I load a saved JSON tree with treelib?


I have made a Python script wherein I process a big html with BeautifulSoup while I build a tree from it using treelib: http://xiaming.me/treelib/. I have found that this library comes with methods to save the tree file on my system and also parsing it to JSON. But after I do this, how can I load it? It is not efficient to build the same entire tree for each run. I think I can make a function to parse the JSON tree previously written to a file but I just want to be sure if there exists another easy way or not.

Thanks in advance


Solution

  • The simple Answer

    With this treelib, you can't.

    As they say in their documentation (http://xiaming.me/treelib/pyapi.html#node-objects):

    tree.save2file(filename[, nid[, level[, idhidden[, filter[, key[, reverse]]]]]]])
        Save the tree into file for offline analysis.
    

    It does not contain any JSON-Parser, so it can not read the files.

    What can you do?

    You have no other option as building the tree each time for every run.

    Implement a JSON-Reader that parses the file and creates the tree for you.

    https://docs.python.org/2/library/json.html