'How can I remove one element in a json string in Python? [duplicate]

I have this payload:

payload = {
    "cluster": "analytics",
    "id_pipeline": "123456789",
    "schema_compatibility": "backward",
    "branch": "production"
}    

And I need to remove the element "id_pipeline" and its value ("123456789").

Any suggestions? I made this code but this errors appears: "'str' object does not support item deletion"

for element in payload_data:
    if 'id_pipeline' in element:
        del element['id_pipeline']

The desirable output payload is something like this:

payload = {
    "cluster": "analytics",
    "schema_compatibility": "backward",
    "branch": "production"
}  

Obs: I need to keep json format.



Solution 1:[1]

You can use del function to remove the selected key from the existing dictionary. Also adding a good read for better understanding - https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/

payload = {
    "cluster": "analytics",
    "id_pipeline": "123456789",
    "schema_compatibility": "backward",
    "branch": "production"
}    

del payload['id_pipeline']

print(payload)

#OUT PUT

{ "cluster": "analytics", "schema_compatibility": "backward", "branch": "production" }

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jijo Alexander