我有 JSON 檔案“json_HW.json”,其中有這種格式的 JSON:
{
"news": [
{
"content": "Prices on gasoline have soared on 40%",
"city": "Minsk",
"news_date_and_time": "21/03/2022"
},
{
"content": "European shares fall on weak earnings",
"city": "Minsk",
"news_date_and_time": "19/03/2022"
}
],
"ad": [
{
"content": "Rent a flat in the center of Brest for a month",
"city": "Brest",
"days": 15,
"ad_start_date": "15/03/2022"
},
{
"content": "Sell a bookshelf",
"city": "Mogilev",
"days": 7,
"ad_start_date": "20/03/2022"
}
],
"coupon": [
{
"content": "BIG sales up to 50%!",
"city": "Grodno",
"days": 5,
"shop": "Marko",
"coupon_start_date": "17/03/2022"
}
]
}
I need to delete field_name and field_value with their keys when I reach them until the whole information in the file is deleted. When there is no information in the file, I need to delete the file itself
The code I have
data = json.load(open('json_HW.json'))
for category, posts in data.items():
for post in posts:
for field_name, field_value in post.items():
del field_name, field_value
print(data)
But the variable data doesn't change when I delete and delete doesn't work. If it worked I could rewrite my JSON
uj5u.com熱心網友回復:
從字典中提取它們后,您正在洗掉鍵和值,這不會影響字典。你應該做的是洗掉字典條目:
import json
import os
file_name = 'json_HW.json'
data = json.load(open(file_name))
for category in list(data.keys()):
posts = data[category]
elem_indices = []
for idx, post in enumerate(posts):
for field_name in list(post.keys()):
del post[field_name]
if not post:
elem_indices.insert(0, idx) # so you get reverse order
for idx in elem_indices:
del posts[idx]
if not posts:
del data[category]
print(data)
if not data:
print('deleting', file_name)
os.unlink(file_name)
這使:
{}
deleting json_HW.json
請注意,這list()是必要的,post.keys()是一個生成器,當您迭代其鍵(或專案或值)時,您無法更改 dict。
uj5u.com熱心網友回復:
如果要從字典中洗掉鍵值,可以使用 del post[key]。但我認為它不適用于迭代,因為字典大小不斷變化。 https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452160.html
