【问题标题】:Removing nested json key-value pair from object by reference in python在python中通过引用从对象中删除嵌套的json键值对
【发布时间】: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


    【解决方案1】:

    使用exec() 命令有效。

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

    输出:

    [{'resource': {'attributes': [{'attribute': 'name'},
                                  {'attribute': 'weight', 'value': '170'}],
                   'id': '9451bf03-665c-4b4f-9836-066b4185334c',
                   'resourceType': 'human'},
      'version': '2021a'}]
    
    

    感谢James Welch 他建议使用eval(),即使它不起作用。搜索eval() 失败的原因我遇到了another post,它推荐exec() 而不是eval()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 2018-07-06
      • 1970-01-01
      • 2020-12-27
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多