我得到错误期望值:第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)

当前回答

即使在调用decode()之后,也可能有嵌入的0。使用替代():

import json
struct = {}
try:
    response_json = response_json.decode('utf-8').replace('\0', '')
    struct = json.loads(response_json)
except:
    print('bad json: ', response_json)
return struct

其他回答

我在一个基于python的web API的响应.text中收到了这样一个错误,但它把我带到了这里,所以这可能会帮助其他人解决类似的问题(在使用请求时,很难在搜索中过滤响应和请求问题..)

在请求数据arg上使用JSON .dumps()创建一个正确转义的JSON字符串,然后再发布,为我修复了这个问题

requests.post(url, data=json.dumps(data))

检查响应数据体,是否有实际数据,数据转储格式是否正确。

在大多数情况下,你的json。JSONDecodeError:期望值:第1行第1列(字符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()

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

一定要记得在文件的内容上调用JSON .loads(),而不是JSON的文件路径:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

我认为很多人都会时不时地这样做(包括我自己):

contents = json.load(json_file_path)

对我来说,这是服务器响应的东西,而不是200,响应不是json格式的。我最终在json解析之前这样做:

# this is the https request for data in json format
response_json = requests.get() 

# only proceed if I have a 200 response which is saved in status_code
if (response_json.status_code == 200):  
     response = response_json.json() #converting from json to dictionary using json library

你的代码产生了一个空的响应体,你会想要检查它或者捕获异常。有可能服务器响应了204 No Content响应,或者返回了一个非200范围的状态码(404 Not Found等)。检查这个。

注意:

没有必要使用simplejson库,Python中包含了与json模块相同的库。 没有必要解码从UTF8到unicode的响应,simplejson / json .loads()方法可以原生处理UTF8编码的数据。 pycurl的API非常古老。除非您对使用它有特定的要求,否则还有更好的选择。

无论是请求还是httpx都提供了更友好的api,包括JSON支持。如果可以,把你的电话换成:

import requests

response = requests.get(url)
response.raise_for_status()  # raises exception when not a 2xx response
if response.status_code != 204:
    return response.json()

当然,这并不能保护您免受不符合HTTP标准的URL的影响;当可能使用任意url时,检查服务器是否打算通过检查Content-Type头来给你JSON,并捕捉异常:

if (
    response.status_code != 204 and
    response.headers["content-type"].strip().startswith("application/json")
):
    try:
        return response.json()
    except ValueError:
        # decide how to handle a server that's misbehaving to this extent