This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Eric McCormick
about 11 years

Failed Lookup, Claims Invalid Syntax (I Say Shenanigans!)

Getting a result of:

Traceback (most recent call last):
  File "runner.py", line 125, in compilecode
  File "python", line 12
     for story in json_obj['list']['story']
                                         ^
SyntaxError: invalid syntax

This should work. My URL and parameters are formed correctly, my variables are defined (contrary to the tooltip that shows up asking if I’ve defined the response variable). Tried the suggestions from the other couple Q&A threads that seemed relevant. Tried clearing browser cache, changing browsers, re-wrote everything, created the URL as a single string (statically defined), and a few other things. Can anyone help me out? Code below:

from urllib2 import urlopen
from json import load

url = "http://api.npr.org/query?apiKey="
key = "API_KEY"
numResults = 3
format = json
id = 1001
url += key+"&numResults="+numResults+"&format="+format+"&id="+id
response = url.urlopen()
json_obj = response.load()
for story in json_obj['list']['story']
    print story['title']['$text']

Edit: I also went and created my own NPR account (for an API), and tested the call and got back valid data directly in-browser.

Answer 514b0927768268f23f00206e

1 vote
Best answer

Permalink

Turns out it was a combination of things:

  • Colon at the end of the for statement
  • Parameters need to all be strings
  • I had tried urlopen(url) (before switching to url.urlopen()), had to switch it back
  • response variable message had nothing to do with what was going on (when I started noticing a ~”string expected int received” error in the console, that clued me in)
points
Submitted by Eric McCormick
about 11 years

Answer 514b079c05268d95c600206d

0 votes

Permalink

the problem is in the response and json variables it seems. I did it like you the first time and kept failing.

Try declaring the variable response like such: urlopen(url) the same for json_obj .

Also in your loop you forgot to add the “:” at the end of the line ;)

points
Submitted by Fábio Rosado
about 11 years