programing

아무것도 반환되지 않은 경우의 JSON 디코드 오류 처리

randomtip 2023. 3. 22. 22:56
반응형

아무것도 반환되지 않은 경우의 JSON 디코드 오류 처리

json 데이터를 해석하고 있습니다.파싱에 문제가 없고 사용 중입니다.simplejson모듈.그러나 일부 API 요청은 빈 값을 반환합니다.다음은 예를 제시하겠습니다.

{
"all" : {
    "count" : 0,
    "questions" : [     ]
    }
}

이것은 json 객체를 해석하는 코드 세그먼트입니다.

 qByUser = byUsrUrlObj.read()
 qUserData = json.loads(qByUser).decode('utf-8')
 questionSubjs = qUserData["all"]["questions"]

일부 요청에 대해 언급했듯이 다음과 같은 오류가 발생합니다.

Traceback (most recent call last):
  File "YahooQueryData.py", line 164, in <module>
    qUserData = json.loads(qByUser)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 420, in raw_decode
    raise JSONDecodeError("No JSON object could be decoded", s, idx)
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

이 오류를 해결하는 가장 좋은 방법은 무엇입니까?

Python 프로그래밍에는 "권한보다 용서를 구하는 것이 더 쉽다"라는 규칙이 있습니다(간단히: EAFP).즉, 값의 유효성을 확인하는 대신 예외를 포착해야 합니다.

따라서 다음을 시도해 보십시오.

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print('Decoding JSON has failed')

편집: 이후simplejson.decoder.JSONDecodeError실제로 계승하다ValueError(여기에 증명합니다), 저는 단지 다음을 사용하여 캐치스테이트먼트를 간략화했습니다.ValueError.

를 Import 해도 괜찮으시다면json모듈을 사용하는 것이 가장 좋은 방법입니다.json.JSONDecodeError(또는json.decoder.JSONDecodeError같은 디폴트 에러를 사용하는 것과 같습니다.ValueError는 json 디코딩에 반드시 연결되어 있지 않은 다른 예외도 포착할 수 있습니다.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//편집(2020년 10월):

@Jacob Lee가 댓글에서 언급했듯이 기본적인 공통점이 있을 수 있습니다.TypeErrorJSON 객체가 다음 값이 아닐 때 발생합니다.str,bytes, 또는bytearray당신의 질문은JSONDecodeError단, 여기서 메모로 언급하는 것이 좋습니다.이 상황을 처리하면서 다른 문제를 구별하려면 다음 사항을 사용할 수 있습니다.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

언급URL : https://stackoverflow.com/questions/8381193/handle-json-decode-error-when-nothing-returned

반응형