dtc348
dtc348

Reputation: 364

delete json objects, if valued matching

I want to delete json objects if value found in the json body. Please see below code and json body. I tried in python but getting error : [TypeError: list indices must be integers or slices, not str]

   import json
   import sys
   key = ['1']
   myData = [
     {
  "id": 1,
  "modifiedBy": "admin",
  "fields": {
    "Application": "1",
    "Endtermin": 23011990
    }
  },
  {
  "id": 2,
  "modifiedBy": "admin",
  "fields": {
    "Application": "2",
    "Endtermin": 11021990
    }
  }
  ]
 #  delete json objects.
 [x for x in myData['fields'] if x["Application"] != 'key']

For example : In the json body, I will look for the Application value, when matching with key, then I want to delete json objects. Here i want to delete first json objects because key value is matching with Application value.

My results looks like here.

    myData = [
       {
         "id": 2,
         "modifiedBy": "admin",
         "fields": {
            "Application": "2",
            "Endtermin": 11021990
          }
      }
      ]

Upvotes: 0

Views: 763

Answers (2)

Tobias Brösamle
Tobias Brösamle

Reputation: 598

You mixed several things up here.

  1. myData is a list, therefore you cannot access any item in it via a string (that's what the error tells you)
  2. You should not check for 'key', but for key[0]
  3. key does not need to be a list

So here's how to fix this:

import json
import sys
key = "1" # point 3 from above
myData = [
  {
    "id": 1,
    "modifiedBy": "admin",
    "fields": {
      "Application": "1",
      "Endtermin": 23011990
    }
  },
  {
    "id": 2,
    "modifiedBy": "admin",
    "fields": {
      "Application": "2",
      "Endtermin": 11021990
    }
  }
]
#  delete json objects. This overwrites myData
myData = [x for x in myData if x["fields"]["Application"] != key] # points 1 and 2

If you really need key to be a list because it may contain several keys, I'd suggest following changes:

keys = ["1", "5"]
# myData is still the same
# ...
myData = [x for x in myData if x["fields"]["Application"] not in keys]

Upvotes: 1

lwohlhart
lwohlhart

Reputation: 1932

This should yield your desired filtering

[x for x in myData if x['fields']['Application'] not in key]

iterates over the list of entries in myData and check for each entry x whether it's property x['fields']['Application'] is not in the list of key which you want to filter

Full code:

import json
import sys
key = ['1']
myData = [
  {
    "id": 1,
    "modifiedBy": "admin",
    "fields": {
      "Application": "1",
      "Endtermin": 23011990
    }
  },
  {
    "id": 2,
    "modifiedBy": "admin",
    "fields": {
      "Application": "2",
      "Endtermin": 11021990
    }
  }
]
#  delete json objects.
myData2 = [x for x in myData if x['fields']['Application'] not in key]

print(myData2)

Upvotes: 1

Related Questions