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
          }
      }
      ]

Answers 1

  • 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]
    

Related Articles