从 JSON 加载数据的那一刻,data = json.loads(request.data)你就有了一个 python 结构。
如果当时它不是字典,那么无论您发送的请求是否包含正确的 JSON 结构(例如,可能是一个列表)。
在这种情况下,我会使用try/ :execept
try:
data = json.loads(request.data)
row = (data['lat'], data['long'], data['address'], data['name'])
except (ValueError, KeyError, TypeError):
# Not valid information, bail out and return an error
return SomeErrorResponse
如果request.data不是有效的 JSON,或者data不是具有正确键的字典,则会引发异常。列出的三个异常是可能的各种错误模式引发的:
>>> import json
>>> json.loads('nonsense')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 338, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> 'ouea'['abc']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str
>>> [0]['oue']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> {}['oue']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'oue'