-1

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.

5
  • 2
    del payload['id_pipeline'] Commented Mar 17, 2022 at 19:23
  • 1
    Do you mean that you have a dict called payload and you want to remove an element? Did you mean del payload["id_pipeline"]? Commented Mar 17, 2022 at 19:23
  • Even if it is a JSON string and not a dictionary, the easiest way is probably to parse it as a dictionary with json.loads, delete the key and write the resulting dictionary back to the JSON file. Commented Mar 17, 2022 at 19:25
  • "I have tried using pop method": Don't just describe what you tried. Show it: Add your code as a minimal reproducible example in a formatted code-block, and tell us why it didn't meet your requirements. Please take the tour and read How to Ask, and the question checklist Commented Mar 17, 2022 at 19:41
  • @Jijo Alexander, thanks, this worked fine. I used a json.dumps(payload) to return to a valid json. Thanks. Commented Mar 17, 2022 at 19:43

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

Such questions have usually already been asked and answered. Since the Stack Overflow community prefers that answers to the same question be consolidated under the same post, the recommended action here is to look for and flag/vote as a duplicate instead of adding an answer to the new question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.