-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.

Nakano
  • 17
  • 1
  • 6
  • 2
    `del payload['id_pipeline']` – John Gordon Mar 17 '22 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"]`? – quamrana Mar 17 '22 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. – jfaccioni Mar 17 '22 at 19:25
  • _"I have tried using pop method"_: Don't just describe what you tried. _Show_ it: Add your code as a [mre] in a [formatted code-block](/help/formatting), and tell us why it didn't meet your requirements. Please take the [tour] and read [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953) – Pranav Hosangadi Mar 17 '22 at 19:41
  • @Jijo Alexander, thanks, this worked fine. I used a json.dumps(payload) to return to a valid json. Thanks. – Nakano Mar 17 '22 at 19:43

1 Answers1

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

Jijo Alexander
  • 1,230
  • 8
  • 17
  • 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. – Pranav Hosangadi Mar 17 '22 at 19:38