skip to Main Content

I have a JSON data. I want to remove the ‘value’ key if only ‘key’ presents.

PFB sample data –

Here I want to remove ‘Job’ and ‘Mob No’ and keep rest of them as it is.

Actual Output –

{
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        },
        {
          "key": "Job"
        },
        {
          "key": "Mob No"
        }
      ]
    }
    ]
}

Expected Output –

{
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        }
      ]
    }
]
}

Kindly suggest a way to achieve this.

2

Answers


  1. try iterating through the details list and ckeck each dictionary to see if it contains only the key and no value.
    If so, remove that dictionary.
    Like so:

    for main_item in data['Main']:
        main_item['details'] = [detail for detail in main_item['details'] if 'value' in detail or len(detail) > 1]
    
    
    Login or Signup to reply.
  2. if the structure of the json file is fixed, you can do like this.

    import json
    
    data = json.loads(json_str)
    for i in len(data["Main"]):
        data["Main"][i]["details"] = [datum for datum in data["Main"][i]["details"] if datum["key"] not in keys]
    output = json.dumps(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search