我是 python 新手,在从文本文件中获取输入后,我必须在 python 中构建一棵树,我在文本文件
中有以下数据。我必须使用 Json 使用以下数据在 python 中构建一棵树
{
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 0,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 0,
"children": []
}
]
}
}
我写了下面的代码,但它有语法错误,如果有人能找到它们,我无法纠正
class node:
#Construction of Node with component,status and children
def _init_(self,component=None,status=None,children=None):
self.component = component
self.status = status
if children is None:
self.children = []
else:
self.children = children
#Building Json object from text file
class start:
import json
f=open("json_file.txt")
data=json.load(f)
buildnode(data)
#Construction of tree through recursion
class implementation:
def buildnode(self,ob):
node1= node()
node1.component=ob.component
node1.status=ob.status
node1.children=[]
print 'component',component,'','status',status
for children in ob:
node1.children.add(buildnode(children[i]))
return node1