0

Using Python3, I have a JSON output stored in a variable. The output contains something like this:

    {
    "department": "inventory",
    "products": [
        {
            "color": "red",
            "shape": "circle",
            "size": "large"
        },
        {
            "color": "blue",
            "shape": "square",
            "size": "small"
        },
        {
            "color": "green",
            "shape": "triangle",
            "size": "medium"
        }
    }

I'm trying to remove any object, within the "products" array, that have a value for "size" as "large" or "medium", leaving with a new output of:

    {
    "department": "inventory",
    "products": [
        {
            "color": "blue",
            "shape": "square",
            "size": "small"
        },
    }

I am somewhat successful using a combination of a for statement with an if statement outside of the array using pop, but I can't seem to figure out how to do it just for the objects within the products array.

I have tried the following:

    for element in products
     if last_login[i]["size"] == "medium":
         del element

Which just gives me this:

    KeyError: 0

Please feel free to ask more questions if needed,

Any help would be greatly appreciated!

3
  • 1
    without some work of your own no coding service, look for list comprehension in the doc Commented Sep 18, 2020 at 1:16
  • 1
    Please provide the expected MRE. Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. Commented Sep 18, 2020 at 1:20
  • Yes - apologies... I just updated it with what I tried earlier. Commented Sep 18, 2020 at 1:41

1 Answer 1

4

Instead of deleting you can just filter and reassign

import json

d = json.loads(json_data)
d['products'] = [x for x in d['products'] if x['size'] not in ('large', 'medium')]
Sign up to request clarification or add additional context in comments.

4 Comments

Hello - is there a benefit to doing it this way? Wouldn't this create 2 arrays or am I missing something? If you have some literature on this that I can read that would be awesome! Thx
it just an implementation choice. It's better to create new list instead of deleting elements from list
Ok understood! what does the d before the list variable do and mean? I keep getting "NameError: name 'd' is not defined"
@Awsmike It's parsed json stored in a variable named d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.