You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何通过字符串路径引用删除JSON对象的嵌套键值对

解决方案

核心逻辑:要删除嵌套键,不需要对全路径解引用,只要定位到待删除键的父级对象,再删除对应子键即可,比全路径解引用更简单安全。

方案1:手动拆分路径(最安全,推荐)

把访问路径拆分成层级列表,逐层遍历到父对象后执行删除:

from pprint import pprint

def delete_nested_key(obj, path):
    # 遍历到待删除键的父级对象
    parent = obj
    # 路径除了最后一个元素,剩下的是父对象的访问路径
    for part in path[:-1]:
        parent = parent[part]
    # 删除最后一个键
    del parent[path[-1]]

# 你的原对象
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"
                    }                 
                ]
            }
        }
    ]

# 把硬编码路径拆成层级列表
path = [0, 'resource', 'attributes', 0, 'value']
delete_nested_key(input_obj, path)

pprint(input_obj)

运行后即可得到目标效果,嵌套的value键会被正常移除。

方案2:字符串路径直接执行(仅可控场景使用)

如果你的路径已经是固定格式的字符串,且路径来源完全可控,没有用户输入的不可信内容,可以用exec直接执行删除语句:

mypath = "input_obj[0]['resource']['attributes'][0]['value']"
exec(f"del {mypath}")
pprint(input_obj)

注意:exec会执行传入的任意代码,如果路径包含恶意构造的内容会触发严重的安全漏洞,非完全可控场景绝对不要使用。

内容的提问来源于stack exchange,提问作者Brian Cragun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:36:04