通过迭代从列表值中的 JSON 个嵌套字典中删除

Delete from JSON nested dictionary in list value by iteration

我有 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"
    }
  ]
}

我需要删除 field_namefield_value 当我到达它们时用它们的键直到整个文件中的信息被删除。当文件中没有信息时,我需要删除文件本身

我有的代码

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)

但是当我删除时变量数据没有改变,删除不起作用。如果它有效,我可以重写我的 JSON

您正在删除键和值,在从字典中提取它们之后, 这不影响字典。你应该做的是删除字典条目:

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()是生成器, 在遍历其键(或项目或值)时,您无法更改字典。

如果你想从字典中删除key-value,你可以使用del post[key]。 但我认为它不适用于迭代,因为字典大小不断变化。 https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/