// 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)
答案 0 :(得分: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': {}}]}