Create a json tree from csv list in python

后端 未结 3 1303
一生所求
一生所求 2020-12-19 20:05

I\'m trying to build a json hierarchy from a simple table in python.

The data comes in looking like the following:

id         parent          name
1          


        
3条回答
  •  生来不讨喜
    2020-12-19 20:56

    To assign all child nodes to its parent, you can do two passes over the list of nodes. The first pass adds each node to a UserDict. In the second pass the parent of each node is guaranteed to be in the UserDict so the node can be added to the children of its parent.

    To serialize to JSON a JSONEncoder can be used.

    #!/usr/bin/env python
    
    import sys
    import json
    import UserDict
    
    class Node(object):
        def __init__(self, nid, parent, name):
            self.nid = nid
            self.parent = parent
            self.children = []
            self.name = name
    
    class NodeDict(UserDict.UserDict):
        def addNodes(self, nodes):
            """ Add every node as a child to its parent by doing two passes."""
            for i in (1, 2):
                for node in nodes:
                    self.data[node.nid] = node
                    if node.parent in self.data.keys():
                        if node.parent != "none" and
                           node not in self.data[node.parent].children:
                            self.data[node.parent].children.append(node)
    
    class NodeJSONEncoder(json.JSONEncoder):
        def default(self, node):
            if type(node) == Node:
                return {"nid":node.nid, "name":node.name, "children":node.children}
            raise TypeError("{} is not an instance of Node".format(node))
    
    if __name__ == "__main__":
        nodes = []
    
        with open(sys.argv[1]) as f:
            for row in f.readlines()[1:]:
                nid, parent, name = row.split()
                nodes.append(Node(nid, parent, name))
    
        nodeDict = NodeDict()
        nodeDict.addNodes(nodes)
    
        rootNodes = [node for nid, node in nodeDict.items()
                     if node.parent == "none"]
        for rootNode in rootNodes:
            print NodeJSONEncoder().encode(rootNode)
    

    Result:

    {"name": "test-name-4", "nid": "4", "children":[
         {"name": "test-name-10", "nid": "10", "children":[
             {"name": "test-name-1", "nid": "1", "children":[
                {"name": "test-name-7", "nid": "7", "children": []},
                {"name": "test-name-8", "nid": "8", "children":[
                    {"name": "test-name-9", "nid": "9", "children": []}]}]},
             {"name": "test-name-2", "nid": "2", "children": []},
             {"name": "test-name-5", "nid": "5", "children":[
                 {"name": "test-name-3", "nid": "3", "children": []}]}]}]}
    {"name": "test-name-6", "nid": "6", "children": []}
    

提交回复
热议问题