【发布时间】:2021-12-25 05:47:24
【问题描述】:
我需要从 python json 对象中删除嵌套的键值。 json 中这个嵌套对象的路径以字符串形式提供给我。
如果我硬编码嵌套对象的路径,我可以使用del 命令执行此操作。但是,我不知道如何取消引用字符串以获取嵌套对象。
因此在下面的代码sn-p中,对象在第一个del之后没有变化,但是key-value在第二个del之后被移除了。
from pprint import pprint
input_obj = [
{
"version": "2021a",
"resource": {
"resourceType": "human",
"id": "9451bf03-665c-4b4f-9836-066b4185334c",
"attributes": [
{
"attribute": "name",
"value":
{"firstname": "John",
"last name": "Doe"}
},
{
"attribute": "weight",
"value": "170"
}
]
}
}
]
# fails
mypath = "input_obj" + "[0]['resource']['attributes'][0]['value']"
del mypath
pprint (input_obj)
# works
del input_obj[0]['resource']['attributes'][0]['value']
pprint (input_obj)
第一个 pprint 的输出:
[{'resource': {'attributes': [{'attribute': 'name',
'value': {'firstname': 'John',
'lastname': 'Doe'}},
{'attribute': 'weight', 'value': '170'}],
'id': '9451bf03-665c-4b4f-9836-066b4185334c',
'resourceType': 'human'},
'version': '2021a'}]
第二个 pprint 的输出。 删除了嵌套的键“值”和值结构。
[{'resource': {'attributes': [{'attribute': 'name'},
{'attribute': 'weight', 'value': '170'}],
'id': '9451bf03-665c-4b4f-9836-066b4185334c',
'resourceType': 'human'},
'version': '2021a'}]
第一个del 是删除变量mypath,而不是引用的对象。第二个del 有效,因为它指的是对象的实际部分。
如何取消引用字符串或以与硬引用相同的方式指向对象?
【问题讨论】:
标签: python json object key-value del