[python] JSONDecodeError : 예상 값 : 1 행 1 열 (문자 0)

Expecting value: line 1 column 1 (char 0)JSON을 디코딩하려고 할 때 오류가 발생 합니다.

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)



답변

주석의 대화를 요약하려면 다음을 수행하십시오.

  • simplejson라이브러리 를 사용할 필요가 없으며 json모듈 과 동일한 라이브러리가 Python에 포함되어 있습니다 .

  • UTF8에서 유니 코드로 응답을 디코딩 할 필요가 없으며, simplejson/ json .loads()메소드는 UTF8로 인코딩 된 데이터를 기본적으로 처리 할 수 ​​있습니다.

  • pycurl매우 오래된 API가 있습니다. 사용에 대한 특정 요구 사항이 없으면 더 나은 선택이 있습니다.

requestsJSON 지원을 포함하여 가장 친숙한 API를 제공합니다. 가능하면 통화를 다음으로 교체하십시오.

import requests

return requests.get(url).json()


답변

실제 데이터가 존재하고 데이터 덤프가 올바른 형식으로되어 있는지 응답 데이터 본문을 확인하십시오.

대부분의 경우 json.loadsJSONDecodeError: 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()

참고 : 데이터 내 따옴표는 올바르게 이스케이프되어야합니다


답변

requestslib를 사용하면 JSONDecodeError404와 같은 http 오류 코드가 있고 응답을 JSON으로 구문 분석하려고 할 때 발생할 수 있습니다!

이 경우를 피하려면 먼저 200 (확인)을 확인하거나 오류 발생시이를 제기해야합니다. 덜 비밀스러운 오류 메시지로 실패하기를 바랍니다.

참고 : 주석 서버에 언급 된 Martijn Pieters 가 오류가 발생하면 JSON으로 응답 할 수 있으므로 (구현에 달려 있음) Content-Type헤더를 확인하는 것이 더 안정적입니다.


답변

정신 검사가 실제로 호출하고 있는지 확인하는 것이 유용 할 수 있습니다 – 나는 그것의 가치는 당신이 JSON 파일 자체의 내용을 분석하고 경우에 언급 할 생각 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.loads(json_file_path)


답변

파일의 인코딩 형식을 확인하고 파일을 읽는 동안 해당 인코딩 형식을 사용하십시오. 문제를 해결할 것입니다.

with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
     data = json.load(json_data, strict=False)


답변

많은 경우, 구문 분석하려는 문자열이 비어 있기 때문입니다.

>>> import json
>>> x = json.loads("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json_string미리 비어 있는지 확인하여 해결할 수 있습니다 .

import json

if json_string:
    x = json.loads(json_string)
else:
    // Your logic here
    x = {}


답변

decode ()를 호출 한 후에도 0이 포함될 수 있습니다. replace ()를 사용하십시오.

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