我正在尝试根据字典中的数据构建一棵树。我知道这可以使用递归来实现,但我在解决这个问题时遇到了困难。 目标是构建以下形式的树:
class Tree():
def __init__(self, data) -> None:
self.data = data
self.children = []
def addChildren(self, child):
self.children.append(child)
以下字典应该被“解析”并用树表示。
{
"PaymentCoverageRequestResource":{
"required":[
"accountId",
"paymentCoverageRequestId"
],
"type":"object",
"properties":{
"paymentCoverageRequestId":{
"maxLength":35,
"type":"string",
"description":"Identification of the payment Coverage Request"
},
"payee":{
"maxLength":70,
"type":"string",
"description":"The merchant where the card is accepted as information to the PSU."
},
"instructedAmount":{
"type":"object",
"properties":{
"amount":{
"maxLength":70,
"type":"string",
"description":"The merchant where the card is accepted as information to the PSU."
},
"currency":{
"maxLength":3,
"type":"string",
"description":"The merchant where the card is accepted as information to the PSU."
}
}
},
"accountId":{
"$ref":"another reference"
}
},
"description":"Payment coverage request structure.\nThe request must rely either on a cash account or a payment card.\nThe [instructedAmount] property is the payment account on wihich the request is processed. This amount must be positive.\nAmounts must always be set as positive values.\n",
"example":"{\n \"paymentCoverageRequestId\" : \"MyCoverage123456\",\n \"instructedAmount\" : {\n \"amount\" : 12345.0,\n \"currency\" : \"EUR\"\n },\n \"accountId\" : {\n \"iban\" : \"YY13RDHN98392489481620896668799742\"\n }\n}",
"x-definition-type":"Resources"
}
}
当且仅当一个节点包含键值对时,该节点才被视为父节点
“类型”:“对象”
它的子级是“properties”中找到的所有键值对。
我尝试使用以下代码解决这个问题,但缺乏一些经验。
def parse_json(requestBody : dict):
def parse_json_rec(tree : Tree, requestBody : dict):
#something ?
if len(requestBody) == 0:
return tree
(k, v), = requestBody.items()
requestBody.pop(k)
print(k)
if v['type'] == 'object': # OR ARRAY
parent_node = Tree(k)
print(v)
return parse_json_rec(tree.addChildren(parse_json_rec(parent_node, v), requestBody))
else:
leaf_node = Tree(k)
tree.addChildren(leaf_node)
return parse_json_rec(tree, requestBody)
pass
root = Tree("root")
return parse_json_rec(root, requestBody)
我想要实现的结果是一个包含多个节点的树,如下所示:
PaymentCoverageRequestResource
paymentCoverageRequestId
payee
instructedAmount
amount
currency
accountId
运行此程序时会发生什么?
你做了什么来调试它?
您认为哪里不对,或者您有什么具体问题?
我发现可能给您带来麻烦的几个问题是:
奇怪的模式尝试从输入中弹出项目,并在存在多个叶子时在同一级别上进行递归。
d = {'a':1,'b':2,'c':3} (k,v), = d.items() 回溯(最近一次调用最后一次): 文件“”,第 1 行,位于 ValueError:需要解包的值太多(预期为 1)
考虑一下,只是对属性进行循环,而不是在同一级别上进行递归,我认为这样会更容易理解。
def parse_tree(node):
for k,v in node.items():
if is leaf: ...
if is node: ... tree.addChild(k, parse_tree(v))