如何访问json文件中的子级


i=0
for element in data["system"]:
#print(element)
for index_in, nested_node in enumerate(data["system"][i]["children"]):
print(data["system"][i]["children"][index_in]["name"])
print(str(item.text(0)))
print(nested_node['name'])
if nested_node["name"] == str(item.text(0)):
print("Done")
del nested_node["system"][i]["children"][index_in]["name"]
#del element[index_in]
i = i + 1

JSON:
"system": [
{
"title": "AirConditioning",
"children": [
{
"name": "Samsung"
},
{
"name": "Daikin"
},

for element in data["system"]:
#print(element)
for index_in, nested_node in enumerate(data["system"][i-1]):
print(data["system"][i-1]["children"][index_in])
if nested_node["system"][i-1]["children"][index_in] == str(item.text(0)):
del data["system"][i-1]["children"][index_in]
#del element[index_in]
i = i + 1
print(json.dumps(data, indent=4))
with open("systems_list.json", "w", encoding="utf8") as json_file:
json.dump(data, json_file, indent=4)

我正试图访问json文件中的子文件,并根据if语句进行删除,但我的程序似乎从未进入if语句

访问子级非常简单。

data["system"][index_1]["children"][index_2]["name"] will bring you there.

但是离你的代码很远,

nested_node["children"][index_in]['name']

给您带来一个dict,例如

{
"name": "Samsung"
}

但你把它比作一个字符串:

str(item.text(0))

Dict==Str始终为False。因此,代码永远不会进入if语句。

我认为在这里使用I有点多余,因为您无论如何都在使用for循环。

为什么不这样做:

#open file
with open("systems_list.json", "r", encoding="utf8") as json_file:
nested_json json.load(json_file)
# let's assume this is what it looks like inside nested_json: 
{"parent1" : 
{"child 1": "sample1", "child 2": "sample2"} 
{"parent2" :
{"child 1": "sample1", "child 2": "sample2"} 
}
for element in nested_json:
if element["child 1"] == sample1:
element.pop('hours', None) #this will erase the child based on value

对于数据中的元素:element.pop("小时",无(

将open("systems_list.json","w",encoding="utf8"(作为data_file:json.dump(data,json_file,indent=4(#保存新文件

最新更新