programing

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

new-time 2020. 5. 14. 22:39
반응형

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가 있습니다. 사용에 대한 특정 요구 사항이 없으면 더 나은 선택이 있습니다.

requests

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

import requests

return requests.get(url).json()

실제 데이터가 존재하고 데이터 덤프가 올바른 형식으로 표시되는지 여부에 따라 응답 데이터 본문을 확인하십시오.대부분의 경우

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()

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


 

requests

lib를 사용하면

JSONDecodeError

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

You must first check for 200 (OK) or let it raise on error to avoid this case. I wish it failed with a less cryptic error message.

NOTE: as Martijn Pieters stated in the comments servers can respond with JSON in case of errors (it depends on the implementation), so checking the Content-Type header is more reliable.


check encoding format of your file and use corresponding encoding format while reading file. It will solve your problem.

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

There may be embedded 0's, even after calling decode(). Use 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

A lot of times, this will be because the string you're trying to parse is blank:

>>> 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)

You can remedy by checking whether json_string is empty beforehand:

import json

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

I had exactly this issue using requests. Thanks to Christophe Roussy for his explanation.

To debug, I used:

response = requests.get(url)
logger.info(type(response))

I was getting a 404 response back from the API.


I was having the same problem with requests (the python library). It happened to be the accept-encoding header.

It was set this way: 'accept-encoding': 'gzip, deflate, br'

I simply removed it from the request and stopped getting the error.

참고URL : https://stackoverflow.com/questions/16573332/jsondecodeerror-expecting-value-line-1-column-1-char-0

반응형