JSONDecodeError:应为值:第1行第1列(字符0)

2024-06-26 14:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试解码JSON时遇到错误Expecting value: line 1 column 1 (char 0)

我用于API调用的URL在浏览器中运行良好,但在通过curl请求完成时会出现此错误。下面是我用于curl请求的代码。

错误发生在return 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)

Tags: inpyselfjsonreturnresponsecurlusers
3条回答

检查响应数据体、是否存在实际数据以及数据转储的格式是否正确。

在大多数情况下,您的json.loads-JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误是由于:

  • 不符合JSON的引用
  • XML/HTML输出(即以<;开头的字符串),或
  • 不兼容字符编码

最终错误告诉您,在第一个位置,字符串已经不符合JSON。

因此,如果解析失败,尽管第一眼看到的数据体与JSON类似,但尝试替换数据体的引号:

import sys, json
struct = {}
try:
  try: #try parsing to dict
    dataform = str(response_json).strip("'<>() ").replace('\'', '\"')
    struct = json.loads(dataform)
  except:
    print repr(resonse_json)
    print sys.exc_info()

注意:数据中的引号必须正确转义

在评论中总结对话:

  • 不需要使用simplejson库,Python中包含的库与json模块相同。

  • 不需要解码从UTF8到unicode的响应,simplejson/json.loads()方法可以本地处理UTF8编码的数据。

  • pycurl有一个非常古老的API。除非您对使用它有特定的要求,否则会有更好的选择。

^{}提供了最友好的API,包括JSON支持。如果可以,请将您的电话替换为:

import requests

return requests.get(url).json()

使用requestsJSONDecodeError时,如果有404之类的http错误代码,并尝试将响应解析为JSON,则可能发生这种情况!

您必须首先检查200(正常)或让它在出错时出现,以避免出现这种情况。 我希望它失败,错误信息不那么隐晦。

注意:正如Martijn Pieters在注释中所述,服务器在出现错误时可以用JSON响应(这取决于实现),因此检查Content-Type头更可靠。

相关问题 更多 >