如何跳过没有有效 json 的请求响应?
How do I skip a requests response with no valid json?
我正在使用请求作为地理编码过程的一部分来遍历大量文本和 return 坐标,如下所示:
for t in text:
payload = {"q":t}
located = requests.get("http://localhost:8999/CLIFF-2.1.1/parse/text", params=payload)
l = located.json()
for i in l['results']['places']['focus']:
print i['name']
print i['lat']
print i['lon']
在大多数情况下,这工作正常,但在某些情况下 No JSON object could be decoded
。有没有办法跳过 JSON 的这一点并继续迭代? (也许是 while 循环?)
这可能是一个非常简单的问题,但我似乎找不到答案...可能是我的处理方式全错了。让我知道是否需要澄清。提前致谢!
顺便说一下,text
是由另一个函数生成的文本对象列表。
您可以简单地捕获 json
模块无法解码响应时引发的 ValueError
,然后 continue
迭代 text
:
for t in text:
payload = {"q": t}
located = requests.get("http://localhost:8999/CLIFF-2.1.1/parse/text", params=payload)
try:
l = located.json()
except ValueError:
# No JSON object could be decoded - skip this item
# and continue with the next item in `text`
continue
for i in l['results']['places']['focus']:
print i['name']
print i['lat']
print i['lon']
我正在使用请求作为地理编码过程的一部分来遍历大量文本和 return 坐标,如下所示:
for t in text:
payload = {"q":t}
located = requests.get("http://localhost:8999/CLIFF-2.1.1/parse/text", params=payload)
l = located.json()
for i in l['results']['places']['focus']:
print i['name']
print i['lat']
print i['lon']
在大多数情况下,这工作正常,但在某些情况下 No JSON object could be decoded
。有没有办法跳过 JSON 的这一点并继续迭代? (也许是 while 循环?)
这可能是一个非常简单的问题,但我似乎找不到答案...可能是我的处理方式全错了。让我知道是否需要澄清。提前致谢!
顺便说一下,text
是由另一个函数生成的文本对象列表。
您可以简单地捕获 json
模块无法解码响应时引发的 ValueError
,然后 continue
迭代 text
:
for t in text:
payload = {"q": t}
located = requests.get("http://localhost:8999/CLIFF-2.1.1/parse/text", params=payload)
try:
l = located.json()
except ValueError:
# No JSON object could be decoded - skip this item
# and continue with the next item in `text`
continue
for i in l['results']['places']['focus']:
print i['name']
print i['lat']
print i['lon']