Alex Man
Alex Man

Reputation: 4886

delete child json object python

I am having a dynamic json (data) in python coming from a service, the service also gives me a dynamic string data keyToDelete where I will get the object to delete

for Example 1 lets say if the data value is as given below

{
  "categories": {
    "attributes": {
      "Alcohol": "full_bar",
      "Noise Level": "average",
      "Music": {
        "dj": false
      },
      "Attire": "casual",
      "Ambience": {
        "romantic": false,
        "intimate": false,
        "touristy": false,
        "hipster": false
      }
    }
  }
}

which means it should delete the Ambience object that comes under attributes, actual result should be like

{
  "categories": {
    "attributes": {
      "Alcohol": "full_bar",
      "Noise Level": "average",
      "Music": {
        "dj": false
      },
      "Attire": "casual"
    }
  }
}

but how to create the above deletion programmatically using python from dynamic keyToDelete

Can anyone please help me on this

Upvotes: 2

Views: 1216

Answers (2)

karthik reddy
karthik reddy

Reputation: 479

snap shot please try this.

def deleteKey(data,keyList): if len(keyList) > 1: data[keyList[0]] = deleteKey(data[keyList[0]],keyList[1:]) else: del data[keyList[0]] return data deleteKey(data,keyToDelete.split("."))

Upvotes: 4

taras
taras

Reputation: 3705

The idea is to iterate through dictionary and the remove the found key. Here is an example:

data = {
  "categories": {
    "imageData": {
      "Alcohol": "xyz123",
      "Noise Level": "average",
      "Music": {
        "dj": False
      },
      "Attire": "casual"
    }
  }
}

for toDelete in ['categories.imageData.Music.dj', 'categories.imageData.Attire']:
    # find keys
    path = toDelete.split('.')
    # remember last item. 
    # It is important to understand that stored value is a reference.
    # so when you delete the object by its key, you are modifying a referenced dictionary/object.
    item = data

    # iterate through all items except last one 
    # we want to delete the 'dj', not 'False' which is its value 
    for key in path[:-1]:
        item = item[key]

    del item[path[-1]]

print data

Result

{'categories': {'imageData': {'Music': {}, 'Alcohol': 'xyz123', 'Noise Level': 'average'}}}

Upvotes: 3

Related Questions