我正在从 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
请您参考如下方法:
你需要先从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()
json_string 现在包含您寻找的 json,假设 api 调用正确返回它。
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)
