First i know how to read .JSON file, but now i confused how to delete partial nested. As you can see i use clear()
method to clear nested JSON, why? When i want to use remove(i)
, it works, but not removing what i want, just make the JSON file got an error
Before
{"dump data": [
{
"dump detail": [
{
"dumper": "MorpKnight",
"title": "test"
}
]
},
{
"dump detail": [
{
"dumper": "MorpKnight",
"title": "test 2"
}
]
}
]
}
After (The one i want as result)
{"dump data": [
{
"dump detail": [
{
"dumper": "MorpKnight",
"title": "test"
}
]
}
And this is my code
data_name = input("Search data")
with open('config.json', "r ") as file:
json_load = json.load(file)
for i in json_load['dump data']:
for j in i['dump detail']:
if j['title'] == data_name:
i.clear()
print("Deleted")
return
CodePudding user response:
You cannot remove items from a list while iterating over it, it's a bad idea unless you do it in reverse and it's not efficient nonetheless.
This however should work:
import json
data_name = input("Search data")
with open('config.json', "r ") as file:
json_load = json.load(file)
new_details = []
for detail in json_load['dump data']:
if all(data['title'] != data_name for data in detail['dump detail']):
new_details.append(detail)
json_load['dump data'] = new_details
I recreate the details list per your specification. You may then save json_load
back into the file if you wish.
CodePudding user response:
data = {"dump data": [
{
"dump detail": [
{
"dumper": "MorpKnight",
"title": "test"
}
]
},
{
"dump detail": [
{
"dumper": "MorpKnight",
"title": "test 2"
}
]
}
]
}
def clean(data, data_name):
data_clean = {'dump data': []}
for i, e in enumerate(data['dump data']):
if e['dump detail'][0]['title'] != data_name:
data_clean['dump data'] = e
return data_clean
data_name = input("Search data: ")
data_clean = clean(data, data_name)
print(data_clean)
prints
Search data: test 2
{'dump data': [{'dump detail': [{'dumper': 'MorpKnight', 'title': 'test'}]}]}