我正在从url获取API,比如:http://api.example.com/search/foo/bar
使用这个简单的代码。
import json
url = "http://api.example.com/search/foo/bar"
result = json.loads(url) # result is now a dict
print result['name']
但是,我得到了这个错误。
Traceback (most recent call last):
File "index.py", line 6, in <module>
result = json.loads(url);
File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
发布于 2015-09-26 16:02:26
您需要先从url读取数据。json.loads()
从字符串加载json。但该字符串本质上只是字符串形式的json结构。您需要通过读取url请求中的数据来获取json字符串,该请求应该是json字符串。
例如,类似这样的事情:
import json
import urllib2
url = "http://api.example.com/search/foo/bar"
response = urllib2.urlopen(url)
json_string = response.read()
假设api调用正确返回,json_string
现在包含您所寻求的json。
json_dict = json.loads(json_string)
您应该能够使用json_dict['name']
等访问json中的项。
json.loads()
从字符串加载json,这就是上面所做的工作(以及为什么我使用read()
来获取字符串)。json.load()
从json对象加载。如果api返回的是您在注释中提到的纯json格式,您可以尝试这样做:
response = urllib2.urlopen(url)
json_dict = json.load(response)
https://stackoverflow.com/questions/32803216
复制