I have a json file test.json,
{
"person": [
{
"requestId": "0",
"name": "ABC",
"age" : 30,
"city": ""
}
]
}
Since city is null I dont want that in the json. so it should be like
{
"person": [
{
"requestId": "0",
"name": "ABC",
"age" : 30,
}
]
}
Also i wanted to update the same test.json file after removing null keys.
This is what I did and it did not remove the record.
with open('test.json') as f:
json_dict = json.load(f)
for key in json_dict:
if json_dict[key] is None:
json_dict.pop(key)
Do I need to check value of the key separately?
2
Answers
I think there are a few problems in your initial approach:
"person"
, which has a non-empty value. So that key is not being removed."city"
which has a value of""
, but you’re comparing""
toNone
.Here’s some code that addresses these problems:
This code loads a JSON object, traverses the whole object, and deletes any dictionary keys whose values are the empty string.
As pointed out in the previous answer, there are 3 issues:
none
in json, but is it an empty string (string len = 0) in python.If you know the structure, then you can do this:
which will return this:
Alternatively, for a more general solution, you should use a recursive method that traverses the structure of the
object
.