prosource

"No JSON object could be decoded"보다 더 나은 오류 메시지 표시

probook 2023. 2. 12. 18:01
반응형

"No JSON object could be decoded"보다 더 나은 오류 메시지 표시

길고 복잡한 JSON 파일에서 데이터를 로드하는 Python 코드:

with open(filename, "r") as f:
  data = json.loads(f.read())

(주의: 최적의 코드 버전은 다음과 같습니다.

with open(filename, "r") as f:
  data = json.load(f)

하지만 둘 다 비슷한 행동을 보인다.)

많은 유형의 JSON 오류(구분자 누락, 문자열 백슬래시 오류 등)의 경우 JSON 오류가 발견된 행과 열 번호가 포함된 유용한 메시지가 출력됩니다.

그러나 다른 유형의 JSON 오류('목록의 마지막 항목에 쉼표 사용'을 포함)와 true/false 대문자와 같은 다른 유형의 경우 Python의 출력은 다음과 같습니다.

Traceback (most recent call last):
  File "myfile.py", line 8, in myfunction
    config = json.loads(f.read())
  File "c:\python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "c:\python27\lib\json\decoder.py", line 360, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\python27\lib\json\decoder.py", line 378, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

이러한 유형의 ValueError를 위해 Python이 JSON 파일의 어디에 오류가 있는지 알려주려면 어떻게 해야 합니까?

가 the i i i i i i i i가simplejson에서는, , 에러가 보다 알기 됩니다.json모듈이 모호합니다.예를 들어 목록의 마지막 항목 뒤에 쉼표가 있는 경우:

json.loads('[1,2,]')
....
ValueError: No JSON object could be decoded

설명이 잘 안 되는 부분이죠와 같은 조작을 실시합니다.simplejson:

simplejson.loads('[1,2,]')
...
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)

★★★★★★★★★★★★★★★★★!하는 등 입니다.True.

Python에게 JSON이 올바르지 않은 위치를 알려줄 수 없습니다.이런 에서 온라인 린터를 사용해야 합니다.

그러면 디코딩하려는 JSON 오류가 표시됩니다.

rson 라이브러리는 http://code.google.com/p/rson/ 에서 사용할 수 있습니다.PYPI https://pypi.python.org/pypi/rson/0.9 에서도 사용할 수 있습니다.그러면 easy_install 또는 pip을 사용하여 얻을 수 있습니다.

예를 들어 톰이 제시한 예:

>>> rson.loads('[1,2,]')
...
rson.base.tokenizer.RSONDecodeError: Unexpected trailing comma: line 1, column 6, text ']'

RSON은 JSON의 슈퍼셋이 되도록 설계되어 있기 때문에 JSON 파일을 해석할 수 있습니다.그것은 또한 인간이 보고 편집하기에 훨씬 좋은 대체 구문을 가지고 있다.입력 파일에 꽤 많이 사용하고 있습니다.

부울값의 대문자화에 대해서는 rson이 부울을 문자열로 잘못 읽습니다.

>>> rson.loads('[true,False]')
[True, u'False']

나도 비슷한 문제가 있었는데 그것은 작은 인용문 때문이었다.JSON 표준(http://json.org)은 큰따옴표를 사용하는 것에 대해서만 언급하고 있기 때문에 python은 반드시json이치노

는, 「기능 을해 보았습니다.load_json_file(path)의 범위 내에서packaging.pyprint★★★★★★★★★★★★★★★★★★:

def load_json_file(path):
    data = open(path, 'r').read()
    print data
    try:
        return Bunch(json.loads(data))
    except ValueError, e:
        raise MalformedJsonFileError('%s when reading "%s"' % (str(e),
                                                               path))

이렇게 하면 트라이캐치에 들어가기 전에 json 파일의 내용을 출력할 수 있습니다.그렇게 하면 Python에 대한 지식이 거의 없어도 구성이 json 파일을 읽을 수 없는 이유를 금방 알 수 있었습니다.
BOM을 studpy) (UTF-8 BOM을 쓰도록 설정했습니다.) (UTF-8 BOM은...) □□□□□□□□★

OP의 특정 문제에 대한 좋은 해답은 아닐지 몰라도, 이것은 매우 억압적인 버그의 원인을 알아내는 데 다소 빠른 방법이었기 때문입니다. 보다 많은 이 이 하게 될 입니다. 그들은 보다 상세한 솔루션을 찾고 있습니다.MalformedJsonFileError: No JSON object could be decoded when reading …그럼 도움이 될 거야

으로 는 asjson파일을 사용하고 .json비단뱀

후 ★★★simplejson타타에 sudo pip install simplejson.

그리고 그걸 해결했죠

import json
import simplejson


def test_parse_json():
    f_path = '/home/hello/_data.json'
    with open(f_path) as f:
        # j_data = json.load(f)      # ValueError: No JSON object could be decoded
        j_data = simplejson.load(f)  # right
    lst_img = j_data['images']['image']
    print lst_img[0]


if __name__ == '__main__':
    test_parse_json()

비슷한 문제가 있었습니다.이것은 제 코드입니다.

    json_file=json.dumps(pyJson)
    file = open("list.json",'w')
    file.write(json_file)  

    json_file = open("list.json","r")
    json_decoded = json.load(json_file)
    print json_decoded

는 내가 file.close()나는 그것을 했고 문제를 해결했다.

그 문제를 해결하려면 인정된 답이 가장 쉽다.그러나 귀사의 정책상 simplejson 설치가 허용되지 않는 경우 "목록의 마지막 항목에 쉼표 사용"이라는 특정 문제를 해결하기 위해 아래 솔루션을 제안합니다.

  1. 자녀 클래스 "JSONLintCheck"를 생성하여 클래스 "JSONDecoder"에서 상속하고 클래스 "JSONDecoder"의 초기 메서드를 다음과 같이 덮어씁니다.

    def __init__(self, encoding=None, object_hook=None, parse_float=None,parse_int=None, parse_constant=None, strict=True,object_pairs_hook=None)        
            super(JSONLintCheck,self).__init__(encoding=None, object_hook=None,      parse_float=None,parse_int=None, parse_constant=None, strict=True,object_pairs_hook=None)
            self.scan_once = make_scanner(self)
    
  1. make_filename은 상기 클래스의 'scan_once' 메서드를 덮어쓰기 위해 사용되는 새로운 함수입니다.그 코드는 다음과 같습니다.
  1 #!/usr/bin/env python
  2 from json import JSONDecoder
  3 from json import decoder
  4 import re
  5
  6 NUMBER_RE = re.compile(
  7     r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
  8     (re.VERBOSE | re.MULTILINE | re.DOTALL))
  9
 10 def py_make_scanner(context):
 11     parse_object = context.parse_object
 12     parse_array = context.parse_array
 13     parse_string = context.parse_string
 14     match_number = NUMBER_RE.match
 15     encoding = context.encoding
 16     strict = context.strict
 17     parse_float = context.parse_float
 18     parse_int = context.parse_int
 19     parse_constant = context.parse_constant
 20     object_hook = context.object_hook
 21     object_pairs_hook = context.object_pairs_hook
 22
 23     def _scan_once(string, idx):
 24         try:
 25             nextchar = string[idx]
 26         except IndexError:
 27             raise ValueError(decoder.errmsg("Could not get the next character",string,idx))
 28             #raise StopIteration
 29
 30         if nextchar == '"':
 31             return parse_string(string, idx + 1, encoding, strict)
 32         elif nextchar == '{':
 33             return parse_object((string, idx + 1), encoding, strict,
 34                 _scan_once, object_hook, object_pairs_hook)
 35         elif nextchar == '[':
 36             return parse_array((string, idx + 1), _scan_once)
 37         elif nextchar == 'n' and string[idx:idx + 4] == 'null':
 38             return None, idx + 4
 39         elif nextchar == 't' and string[idx:idx + 4] == 'true':
 40             return True, idx + 4
 41         elif nextchar == 'f' and string[idx:idx + 5] == 'false':
 42             return False, idx + 5
 43
 44         m = match_number(string, idx)
 45         if m is not None:
 46             integer, frac, exp = m.groups()
 47             if frac or exp:
 48                 res = parse_float(integer + (frac or '') + (exp or ''))
 49             else:
 50                 res = parse_int(integer)
 51             return res, m.end()
 52         elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
 53             return parse_constant('NaN'), idx + 3
 54         elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
 55             return parse_constant('Infinity'), idx + 8
 56         elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
 57             return parse_constant('-Infinity'), idx + 9
 58         else:
 59             #raise StopIteration   # Here is where needs modification
 60             raise ValueError(decoder.errmsg("Expecting propert name enclosed in double quotes",string,idx))
 61     return _scan_once
 62
 63 make_scanner = py_make_scanner
  1. 'make_scanner' 함수를 새 자식 클래스와 함께 동일한 파일에 넣는 것이 좋습니다.

같은 , 내 는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★BOM파일 선두에 (바이트 순서 마크)가 표시됩니다.

json.toolUTF BOM 마크를 삭제할 때까지 빈 파일(괄호만)도 처리하지 않습니다.

내가 한 일은:

  • vim으로 json 파일을 열어서
  • 순서 마크( 「」 「」( 「」)set nobomb)
  • 파일 저장

이로써 json.tool의 문제가 해결되었습니다.이게 도움이 됐으면 좋겠네요!

파일이 생성되었을 때.내용이 비어 있는 파일을 만드는 대신,대체 대상:

json.dump({}, file)

순수 피톤 구현보다 최대 250배 빠른 cjson을 사용할 수 있습니다.이는 "오래되고 복잡한 JSON 파일"이 있기 때문에 여러 번 실행해야 하기 때문입니다(디코더에 장애가 발생하여 처음 발생한 오류만 보고합니다).

언급URL : https://stackoverflow.com/questions/14899506/displaying-better-error-message-than-no-json-object-could-be-decoded

반응형