0

So I'm attempting to learn how to search the output of trakt.tv's api and return only the information for a certain show. The json ouput is as follows

[
  {
      "title": "NCIS",
      "year" : 2003,
      "url": "blah"
    },
   {   
       "title": "Jeffersons",
       "year" : 1902,
       "url": "notreally"
     }
]

:edited code for correct formatting.

I'm trying to find only the information for the title NCIS. and I've run into a problem getting the information. Possibly because everything i've seen deals with json.dump or json.loads and i'm trying to do this with data = json.load(urllib2.urlopen(url))

I basically only want to display show:0 if title matches NCIS. I'm just not sure how.

3
  • What trakt.tv API method are you using? Commented Mar 1, 2013 at 18:55
  • Then your example JSON misrepresents the actual output, as far as the documentation for search/shows is concerned. Commented Mar 1, 2013 at 19:16
  • then i probably mistyped it seeing as i have 15 windows open Commented Mar 1, 2013 at 19:18

1 Answer 1

4

The /search/shows API method returns a list of shows (each a mapping) that match your search.

You can simply loop over these and match the specific title:

data = json.load(urllib2.urlopen(url))

for show in data:
    if show['title'] == 'NCIS':
        # matching show

or you could use a generator expression to get one matching show:

try:
    ncis_show = next(show for show in data if show['title'] == 'NCIS')
except StopIteration:
    ncis_show = None  # not found
Sign up to request clarification or add additional context in comments.

1 Comment

Using next() is very elegant imo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.