简体   繁体   中英

searching json ouput in python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM