I want to remove whole Element array from this below json file. I am quite new in json. Please help.
Input:
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"
}
Output:
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"
}
I tried to keep the json in a file called file.json and executed below code in 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)
But no help.
2
Answers
You executed:
What you wanted was something along the lines of
or
https://docs.python.org/3/library/stdtypes.html#dict.pop
Because
"Element"
is a nested value and not a key, one approach is to loop through the values. Your code should look like: