Rodrigo Leite Rodrigo Leite - 6 months ago 22
JSON Question

Loop through json file and delete key if it matches

I have the following structure on a JSON file:

{
"channels": [
"180873781382873088",
"181268808055521280",
"183484852287307777",
"174886257636147201",
"174521530573651968"
]
}


I want to know how I can loop through the file searching for a specific string, and delete it if it matches.

Thank you.

EDIT: A Google search pointed me to using a for loop and using the del command to remove the key, so here's what I tried:

channel = "180873781382873088"

for item in data['channels']:
del channel


But it only deletes the variable channel, not the key that matches it's value.

Answer

Try

data['channels'].remove(channel)

instead of the for loop.

This will automatically search the array and remove any key matching your variable. If you need help saving the results to a file I would open another question.