하얀설표 블로그




해결)requests.exceptions.JSONDecodeError: Extra data: line * column * (char *)





( 수정됨)


에러

에러 예시

import requests
url = 'https://httpstat.us/200'
with requests.get(url, timeout = 3) as r:
    j = r.json()

>> Traceback (most recent call last):
  File "C:\seolpyo\Lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\json\decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 5 (char 4)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\seolpyo\example.py", line 4, in <module>
    j = r.json()
        ^^^^^^^^
  File "C:\seolpyo\Lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Extra data: line 1 column 5 (char 4)

해결방법

  1. json 형식으로 제공되는 페이지를 r.json() 명령으로 변환한 것인지 확인한다.
  2. 잘못된 문자열을 json에서 인식 가능한 형태로 변환해준다.

설명

문제의 원인은 2가지가 있지만, 대부분의 원인은 1안으로 인한 문제다.
json 형식이 아닌 응답을 json으로 변환하려고 시도했기 때문에 발생하는 것이다.

자신이 응답을 요청한 url을 확인하고, json 형식으로 응답이 오는 것이 맞는지 확인해보자.

응답의 형식은 r.headers.get('content-type') 명령으로 확인이 가능하다.
json 형식의 응답인 경우 application/json이 포함되는 결과를 확인할 수 있다.

2안에 해당하는 경우

json 형식으로 응답이 오지만 잘못된 이스케이프 문자가 들어있는 경우라면 다음과 같이 Extra data가 아닌 다른 에러 메세지가 노출된다.

requests.exceptions.JSONDecodeError: Invalid \escape: line * column * (char *)

이 에러가 발생하는 경우 r.json()명령으로는 해결이 어렵고, r.text 또는 r.content를 받아 이스케이프 문자를 json으로 읽을 수 있도록 변경한 다음 json.loads 명령을 통해 json 객체로 변환시켜야 한다.
이스케이프 문자를 json 형식으로 변환하는 방법은 이 글에서 확인할 수 있다.


공감 : 0







white.seolpyo.com