-1
// obj.json
{
  "first": [
    {
      "second": {
         "third": "value"
      }
    }
  ]
}

在我将 json 加载到 dict 之后,有没有办法像这样删除"value"

path_to_delete = ['first.[0].second.third']
for p in path_to_delete:
    deleteByPath(obj, p)
4

1 回答 1

1

这是一个功能解决方案。识别整数列表索引与字符串键是比较麻烦的部分,但在这里通过列表理解来处理。

d = {"first": [{"second": {"third": "value"}}]}

from functools import reduce
from operator import getitem

def removeFromDict(dataDict, mapStr):
    mapList = [int(i[1:-1]) if i.startswith('[') and i.endswith(']') \
               else i for i in mapStr.split('.')]
    del reduce(getitem, mapList[:-1], dataDict)[mapList[-1]]
    return dataDict

d = removeFromDict(d, 'first.[0].second.third')

print(d)

{'first': [{'second': {}}]}
于 2018-07-04T09:27:35.847 回答