'JSON: Trouble editing a JSON file in Python

What I want to do is remove the array containing "Nike" under the "Shoe" variable.
Here is the Json file:

{
    "Shoes/Colorways":
    [
        {
            "Shoe": "Nike",
            "Colorway": "Blue"
        },
        {
            "Shoe": "Jordan",
            "Colorway": "Blue"
        }
    ]
}

I want the end result of the Json file to look like this:

{
    "Shoes/Colorways":
    [
        {
            "Shoe": "Jordan",
            "Colorway": "Blue"
        }
    ]
}

Here is the code I used to try to remove the array with "Nike":

import json

path = 'keywords.json'

with open(path, 'r') as f:
    data = json.load(f)

for info in data['Shoes/Colorways']:
    if info['Shoe'] == 'Nike':
        data.remove(info['Shoe'])
        data.remove(info['Colorway'])
    else:
        pass
print(data)

Here is the error:

Traceback (most recent call last):
  File "c:\Users\TestUser\Desktop\Projects\Programs\json.py", line 10, in <module>
    data.remove(info['Shoe'])
AttributeError: 'dict' object has no attribute 'remove'

I realized that .remove is only for lists and I cannot seem to find out how to do what I need to do in this scenario.



Solution 1:[1]

Try this:

import json

path = 'keywords.json'

with open(path, 'r') as f:
    data = json.load(f)

data['Shoes/Colorways'] = [info for info in data['Shoes/Colorways'] if info['Shoe'] != 'Nike']

print(data)

Solution 2:[2]

The error is telling you, .remove does not exist on a dict object. Notice carefully that data is a dict. You should be calling .remove on the list - data['Shoes/Colorways'] is the list you need to remove from.

It would, however, be far better to simply use a list comprehension that filters out the element instead

data['Shoes/ColorWays'] = [x for x in data['Shoes/ColorWays'] if x['Shoe'] != 'Nike']

Solution 3:[3]

Remove operation doesn't exist in the dictionary. Better to skip some value that is not necessary.

 print([info for info in data['Shoes/Colorways'] if info['Shoe'] != 'Nike'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sarartur
Solution 2 Chase
Solution 3