我得到错误期望值:第1行第1列(字符0)时试图解码JSON。

我用于API调用的URL在浏览器中工作正常,但在通过curl请求完成时给出了这个错误。下面是我用于curl请求的代码。

错误发生在返回simplejson.loads(response_json)时

response_json = self.web_fetch(url)
response_json = response_json.decode('utf-8')
return json.loads(response_json)


def web_fetch(self, url):
    buffer = StringIO()
    curl = pycurl.Curl()
    curl.setopt(curl.URL, url)
    curl.setopt(curl.TIMEOUT, self.timeout)
    curl.setopt(curl.WRITEFUNCTION, buffer.write)
    curl.perform()
    curl.close()
    response = buffer.getvalue().strip()
    return response

回溯:

File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nab/Desktop/pricestore/pricemodels/views.py" in view_category
  620.     apicall=api.API().search_parts(category_id= str(categoryofpart.api_id), manufacturer = manufacturer, filter = filters, start=(catpage-1)*20, limit=20, sort_by='[["mpn","asc"]]')
File "/Users/nab/Desktop/pricestore/pricemodels/api.py" in search_parts
  176.         return simplejson.loads(response_json)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/__init__.py" in loads
  455.         return _default_decoder.decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in decode
  374.         obj, end = self.raw_decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in raw_decode
  393.         return self.scan_once(s, idx=_w(s, idx).end())

Exception Type: JSONDecodeError at /pricemodels/2/dir/
Exception Value: Expecting value: line 1 column 1 (char 0)

当前回答

当你想在python中加载json文件时,这是我发现的最简单的解决方案

import json
data = json.load(open('file_name.json'))

如果给出错误,表示字符在X和Y位置不匹配,则只需在左圆括号内添加encoding='utf-8'

data = json.load(open('file_name.json', encoding='utf-8'))

解释 Open打开文件并读取稍后在json.load中解析的包含。

请注意,使用与open()作为f比上述语法更可靠,因为它确保文件在执行后关闭,完整的语法将是

with open('file_name.json') as f:
    data = json.load(f)

其他回答

如果你使用header并且有"Accept-Encoding": "gzip, deflate, br",安装brotli库pip install。你不需要将brotli导入py文件。

只需检查请求的状态码是否为200。例如:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"

我有同样的问题,试图读取json文件

json.loads("file.json")

我用

with open("file.json", "r") as read_file:
   data = json.load(read_file)

也许这个对你有帮助

在我的情况下,它发生了,因为我读取文件的数据使用file.read(),然后尝试使用json.load(文件)解析它。我通过将json.load(file)替换为json.loads(data)来解决这个问题。

不能工作的代码

with open("text.json") as file:
    data=file.read()
    json_dict=json.load(file)

工作代码

with open("text.json") as file:
   data=file.read()
   json_dict=json.loads(data)

对我来说,它没有在请求中使用身份验证。