简体   繁体   中英

Removing nested json key-value pair from object by reference in python

I need to remove a nested key-value from a python json object. The path to this nested object in the json is given to me in a string.

I can do this with del command if I hard-code the object. However, I can't figure out how to de-reference the string to get the object.

Thus in the following code snippet, the object is unchanged after the first del , but the key-value is removed after the second del .

input_obj = [
        {
            "version": "2021a",
            "resource": {
                "resourceType": "human",
                "id": "9451bf03-665c-4b4f-9836-066b4185334c",
                "attributes": [
                    {
                        "attribute": "hair-color",
                        "value": "black"
                    },
                    {
                        "attribute": "weight",
                        "value": "170"
                    }                 
                ]
            }
        }
    ]

mypath = "input_obj" + "[0]['resource']['attributes'][0]['value']"
del mypath

del input_obj[0]['resource']['attributes'][0]['value']

The first del is deleting the variable mypath , not the referenced object. The second del works because it refers to an actual part of the object.

How can I de-reference the string or somehow point to the object the same way as the hard reference?

Are you just trying to remove the value or remove the key-value pair from the hierarchy? It is difficult to tell without the outputs after the del statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM