2

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

3
  • Split your keytodelete with '.' . Iterate the list and delete the json Commented Nov 3, 2017 at 7:57
  • but how do we do the iteration....in the above two example the json to delete is the second child....but it may sometimes vary... Commented Nov 3, 2017 at 8:05
  • can u show me an example. Commented Nov 3, 2017 at 8:05

2 Answers 2

4

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("."))

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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.