我需要阅读下面的json响应后的波谷
我正在搜索特殊文件夹的ID。 我知道较深的级别,因为我知道整个路径,所以我希望在其中找到该文件夹。 我需要找回文件夹的ID。
我知道的是我要查找的文件夹的整个路径,例如/ Core / UI / Folder1 / Subfolder2 所以我需要subfolder2的ID。
我尝试了几次循环,但由于进行了深入搜索而失败了。 当然,我可以编写一些深层次的手册,但这听起来并不是我认为的正确方法。
示例JSON
{
"folders": [
{
"rank": 1,
"name": "Core",
"id": 390,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "",
"folders": [
{
"rank": 1,
"name": "UI",
"id": 391,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core",
"folders": [
{
"rank": 1,
"name": "Folder1",
"id": 392,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core/UI",
"folders": [
{
"rank": 1,
"name": "Subfolder2",
"id": 393,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core/UI/Folder1",
"folders": []
}
]
}
]
}
]
}
],
"allTestsCount": 791,
"allOrphanTestsCount": 791
}
答案 0 :(得分:0)
好的,如果我对您的理解正确,那应该可以,请告诉我
data = {
"folders": [
{
"rank": 1,
"name": "Core",
"id": 390,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "",
"folders": [
{
"rank": 1,
"name": "UI",
"id": 391,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core",
"folders": [
{
"rank": 1,
"name": "Folder1",
"id": 392,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core/UI",
"folders": [
{
"rank": 1,
"name": "Subfolder2",
"id": 393,
"testCount": 0,
"totalTestCount": 0,
"testRepositoryPath": "/Core/UI/Folder1",
"folders": []
}
]
}
]
}
]
}
],
"allTestsCount": 791,
"allOrphanTestsCount": 791
}
def extract_inner_id(d, path):
try:
current_path = d['testRepositoryPath'] + '/' + d['name']
if current_path == path:
return d['id']
except KeyError:
pass
for sub_d in d['folders']:
inner_id = extract_inner_id(sub_d, path)
if inner_id is not None:
return inner_id
return None
print(extract_inner_id(data, "/Core/UI/Folder1/Subfolder2"))
请注意,我们从内部为每个子文件夹调用extract_inner_id
,这是无论深度如何我们都可以进行搜索的方式。