简体   繁体   中英

How to remove empty { } from JSON file using python

I have done my research but I couldn't find any answers that worked.

I have the following JSON file:

{
    "Cars": [{
            "Manufacturer": "Audi",
            "model": "R8",
            "price": 50000,
            "a": {
                "n": "1",
                "street": "ABC Street",
                "city": "London",
                "postcode": "TW1 1AA"
            }
        },
        {
            "Manufacturer": "Ford",
            "model": "Fiesta",
            "price": 10000,
            "a": {
                "n": 2,
                "street": "DEF street",
                "town": "London",
                "PostCode": "TW2 2AB"
            }
        },
        {
            "Manufacturer": "VW",
            "model": "Polo",
            "price": 5000,
            "a": {
                "n": "3",
                "Street": "GHI Street",
                "town": "London",
                "postcode": "TW3 3CD"
            }
        }

    ]
}

In my python file, to remove the JSON elements, I am using the following:

deletecar = int(input("Enter price of car to delete: "))
for item in data["Cars"]:
   if deletecar == item["price"]:
      item.pop("Manufacturer")
      item.pop("model")
      item.pop("price")
      item.pop("a")

      with open("testjson.json", 'w') as f:
          json.dump(data, f)

When I run this, if I delete the first car in the JSON file, I find this:

{"Cars": [{}, {"Manufacturer": "Ford", ...

If I now run my program again, but I try to search for cars, the program won't work due to these empty braces.

So how can I remove them using Python?

Thanks in advance.

You need to remove the item itself, which means you need two steps:

  1. find the index at which the item you want to remove is
  2. remove the item from the list (with del )

And you don't need to "empty" the dict as that's not what you're looking for.

Alternatively, you could create a brand new list without the offending item using a list comprehension or a filter call eg

deletecar = int(input("Enter price of car to delete: "))
data['Cars'] = [
    item for item in data['Cars']
    if item['price'] != deletecar
]

with open("testjson.json", 'w') as f:
      json.dump(data, f)

(note: this "removes" all items which match, rather than just the first as your code does).

Also you probably want to save after you're done processing, not during processing.

Since it's a list, you can find the index values in your list that match your price input. Then remove those elements from values in the 'Cars' list

deletecar = int(input("Enter price of car to delete: "))

# Get the index values of where the item is located
index_to_delete = []
for item in data["Cars"]:
   if deletecar == item["price"]:
      index_to_delete.append(data["Cars"].index(item))

# Since the index values will change as you delete them,
# you will have to remove them in reverse order (in case there's more than 1 
# item being removed

for i in reversed(index_to_delete):
    del data["Cars"][i]      

# write to file      
with open("testjson.json", 'w') as f:
    json.dump(data, f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM