有没有办法在python中验证json响应?

时间:2015-09-01 11:30:28

标签: python json python-2.7 python-requests

我正在尝试验证python中的json,这是来自url命中的响应。我如何在python中验证它以确保此响应仅为json?

def SLRCLDQR011():
try:
    url = 'http://someurl.com/q='
    query = 'running shoes'
    resp = requests.get(url + query)

except requests.exceptions.ConnectionError as e:
    print 'Domain Name is not reachable'
except:
    print "testcase {0} failed ".format(funcName)
    logfile.write("testcase {0} failed ".format(funcName))
    print "Unexpected error:", sys.exc_info()[0]
    raise

1 个答案:

答案 0 :(得分:3)

响应对象的方法json会尝试将响应体解析为json

resp = get("https://httpbin.org/ip")
resp.json()
{'origin': '81.89.63.129'}

对于非json响应,它会抛出ValueError

resp = get("https://httpbin.org/")    
resp.json()
...
...
ValueError: Expecting value: line 1 column 1 (char 0)

如果您想验证该json中的内容使用voluptuousjsonschema