如何跳过没有有效json的请求响应?

时间:2015-06-03 19:28:05

标签: json python-2.7 python-requests

我正在使用请求作为地理编码过程的一部分来循环遍历大量文本并返回坐标,如下所示:

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并继续迭代? (也许是一段时间的循环?)

这可能是一个非常简单的问题,但我似乎无法找到答案......而且可能是我接近这一切都错了。如果有任何需要澄清,请告诉我。提前谢谢!

顺便说一句,text是由另一个函数生成的文本对象列表。

1 个答案:

答案 0 :(得分:1)

您可以简单地抓住ValueError模块无法解码响应时引发的json,然后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']