简体   繁体   English

在 Python 中加载 JSON 文件会引发错误。

[英]Loading JSON file in Python throwing an error.

I am fetching an API from url like: http://api.example.com/search/foo/bar我正在从 url 获取 API,例如: http://api.example.com/search/foo/bar : http://api.example.com/search/foo/bar

using this simple code.使用这个简单的代码。

import json
url = "http://api.example.com/search/foo/bar"
result = json.loads(url)  # result is now a dict
print result['name']

But, I am getting this error.但是,我收到此错误。

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

You need to read the data from the url first.您需要先从 url 读取数据。 json.loads() loads the json from a string. json.loads()从字符串中加载 json。 But that string is essentially just the json structure in string form.但该字符串本质上只是字符串形式的 json 结构。 You need to get that json string by reading the data from that url request, which should be the json string.您需要通过从该 url 请求中读取数据来获取该 json 字符串,该数据应该是 json 字符串。

For instance, something like this:例如,这样的事情:

import json
import urllib2
url = "http://api.example.com/search/foo/bar"
response = urllib2.urlopen(url)
json_string = response.read()

json_string now contains the json you seek, assuming that the api call returns it correctly. json_string现在包含您寻找的 json,假设 api 调用正确返回它。

json_dict = json.loads(json_string)

You should be able to access the items in the json with json_dict['name'] etc.您应该能够使用json_dict['name']等访问 json 中的项目。

json.loads() loads the json from a string, which is what is done above(and why I used read() to get the string). json.loads()从字符串中加载 json,这就是上面所做的(也是我使用read()获取字符串的原因)。 json.load() loads from a json object. json.load()从 json 对象加载。 If the api is returning a pure json format as you mentioned in the comments, you could try this instead:如果 api 返回的是你在评论中提到的纯 json 格式,你可以试试这个:

response = urllib2.urlopen(url)
json_dict = json.load(response)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM