删除子json对象python

时间:2017-11-03 07:52:39

标签: python json

我在python中有一个来自服务的动态json( data ),该服务还为我提供了一个动态字符串数据 keyToDelete ,其中我将获取对象删除

示例1 可以说明数据值是否如下所示

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

这意味着它应该删除属性下的 Ambience 对象,实际结果应该像

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

但如何使用动态 keyToDelete

中的python以编程方式创建上述删除

任何人都可以帮助我

2 个答案:

答案 0 :(得分:3)

想法是迭代字典并删除找到的密钥。这是一个例子:

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

结果

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

答案 1 :(得分:3)

snap shot 请试试这个。

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