The idea:
A JSON file should be loaded and the object 2-uID
with its sub-items should be deleted. The edited content should be saved in the same JSON file.
The problem:
I have already tried several approaches, like this one from an SO user, but nothing has worked for me yet.
The code shown does not delete anything, but pushes the content all into one line.
The current code
Python code:
import json
with open("path/to/json") as data_file:
data = json.load(data_file)
for element in data:
if '2-uID' in element:
del element['2-uID']
with open("path/to/json", 'w') as data_file:
data = json.dump(data, data_file)
JSON file:
{
"uID": {
"1-uID": {
"username": "1-username",
"pinned": true
},
"2-uID": {
"username": "2-username",
"pinned": false
},
"3-uID": {
"username": "3-username",
"pinned": false
}
}
}
This is how the JSON file should look like after the process:
{
"uID": {
"1-uID": {
"username": "1-username",
"pinned": true
},
"3-uID": {
"username": "3-username",
"pinned": false
}
}
}
CodePudding user response:
EDIT:
This is your problem:
for element in data:
if '2-uID' in element:
del element['2-uID']
data
is the top-level element, so it only has one key: "uID". Try printing out "element" :)
Maybe I'm misundertanding you, but shouldn't you just use del
?
This works for me
# string holding the JSON object
s = r"""{
"uID": {
"1-uID": {
"username": "1-username",
"pinned": true
},
"2-uID": {
"username": "2-username",
"pinned": false
},
"3-uID": {
"username": "3-username",
"pinned": false
}
}
}"""
import json
j = json.loads(s)
# remove one of the elements
del j["uID"]["2-uID"]
# see that the element is now gone
print(j)
# output:
# {'uID': {'2-uID': {'pinned': False, 'username': '2-username'},
# '3-uID': {'pinned': False, 'username': '3-username'}}}
CodePudding user response:
"with open("path/to/json") as data_file:"
You don't have any mode like read or write etc? Maybe that's the issue? And using pop instead of delete then.