我想从下面的JSON文件中删除整个元素数组。我是一个很新的JSON。请帮助。
- 输入**:
ABCD12:
{
"code": "ab11",
"Number": 123456,
"Name": "aaaaaa",
"Element": [
{
"abc": "123",
"Center": "123",
"Description": "your description here",
},
{
"Cdf": "456",
"Color": "blue",
"Shape": "round",
}
],
"Animal": "tiger",
"Bird": "eagle",
"Flower": "rose"
}
CDEF34:
{
"code": "cd12",
"Number": 7891011,
"Name": "bbbbb",
"Element": [
{
"abc": "345",
"Center": "456ab",
"Description": "your description",
},
{
"Cdf": "567",
"Color": "grey",
"Shape": "circle",
}
],
"Animal": "dog",
"Bird": "crow",
"Flower": "sunflower"
}
- 输出**:
ABCD12:
{
"code": "ab11",
"Number": 123456,
"Name": "aaaaaa",
"Animal": "tiger",
"Bird": "eagle",
"Flower": "rose"
}
CDEF34:
{
"code": "cd12",
"Number": 7891011,
"Name": "bbbbb",
"Animal": "dog",
"Bird": "crow",
"Flower": "sunflower"
}
我尝试将json保存在一个名为file.json的文件中,并在python中执行以下代码
import json
with open("file.json") as f:
data= json.load(f)
f.pop(data["wbsElement"])
with open("file.json", "w") as f:
json.dump(data, f)
但没有帮助。
2条答案
按热度按时间c6ubokkw1#
您执行了:
你想要的是沿着于
或
https://docs.python.org/3/library/stdtypes.html#dict.pop
2wnc66cl2#
因为
"Element"
是一个嵌套的值而不是键,所以一种方法是循环遍历这些值。