Home > Blockchain >  Delete from JSON nested dictionary in list value by iteration
Delete from JSON nested dictionary in list value by iteration

Time:03-25

I have JSON file 'json_HW.json' in which I have this format 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

CodePudding user response:

You are deleting the key and the value, after extracting them from the dictionary, that doesn't affect the dictionary. What you should do is delete the dictionary entry:

import json

data = json.load(open('json_HW.json'))  

for category, posts in data.items():
    for post in posts:
        for field_name in list(post.keys()):
            del post[field_name]


print(data)

which gives:

{'news': [{}, {}], 'ad': [{}, {}], 'coupon': [{}]}

Note that the list() is necessary, post.keys() is a generator and you cannot change the dict while you are iterating over its keys (or items or values).

I assumed test_data should have been data.

CodePudding user response:

if you want to delete key-value from dictionary, you can use del post[key]. but i don't think it works for iteration, cause dictionary size keeps changing. https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/

  • Related