{
"numlist1": [
"num1",
"num2"
],
"numlist2": [
"num1",
"num2"
]
}
This above is my example json file. As you can see it stores two json arrays. Now I tried the following to delete an array of my choice:
import json
with open('numbers.json', 'r ') as json_string:
conv_json = json.load(json_string)
del conv_json["numlist2"]
with open('numbers.json', 'r ') as json_string:
json.dump(conv_json, json_string, indent=2)
This sadly doesn't work. Does someone know, how to do this?
CodePudding user response:
The problem is your second open call: the "r "
mode says to allow overwriting without truncating. Have you looked at the result? You ARE deleting that element, but you are only overwriting the first half of the JSON. What used to be in the file is still there, so it's invalid JSON.
Replace the "r "
with "w"
and all will be well.