1

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.

Rodrigo Leite
  • 596
  • 5
  • 22
  • Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – R Nar May 25 '16 at 17:26
  • You'll need to try something out and ask us for help. You basically wrote out the right approach. What's the problem with that? – TankorSmash May 25 '16 at 17:26
  • I'll edit the question with what I have so far. – Rodrigo Leite May 25 '16 at 17:27
  • Do you want to operate on the file directly, or do you want to read it in to a Python data structure to work with it and then save it back to a file afterwards? – John Gordon May 25 '16 at 17:31
  • Saving it back to a file after working with it would be best, in my opinion, as it's what I'm used to doing. – Rodrigo Leite May 25 '16 at 17:32
  • The overall JSON data is organized as a dictionary, but the specific item you're working with, `data['channels']`, is a list. Lists have a method, `remove()`, that removes the first occurrence of the given value. – John Gordon May 25 '16 at 17:36
  • Thank you, that's exactly what I needed. – Rodrigo Leite May 25 '16 at 17:38

1 Answers1

2

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.

CamJohnson26
  • 1,119
  • 1
  • 15
  • 40