prosource

Python 3에서 JSON 파일 읽기

probook 2023. 2. 27. 22:28
반응형

Python 3에서 JSON 파일 읽기

Windows 10 x 64 에서 Python 3.5.2 를 사용하고 있습니다.JSON내가 읽고 있는 파일은 이 파일이다.JSON2개의 어레이를 더 포함하는 어레이.

난 이걸 해석하려고 해JSON를 사용하여 파일을 작성하다json모듈.문서에서 설명한 바와 같이JSON파일은 다음 조건에 적합해야 합니다.RFC 7159여기서 내 파일을 확인해보니, 그 파일들은 완벽하게 괜찮대.RFC 7159포맷을 합니다만, 다음의 간단한 python 코드를 사용해 읽으려고 하면,

with open(absolute_json_file_path, encoding='utf-8-sig') as json_file:
    text = json_file.read()
    json_data = json.load(json_file)
    print(json_data)

이 예외는 다음과 같습니다.

Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 2217, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 1643, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc) 
  File "C:/Users/Andres Torti/Git-Repos/MCF/Sur3D.App/shapes-json-checker.py", line 14, in <module>
    json_data = json.load(json_file)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Javascript에서는 이 파일을 완벽하게 읽을 수 있지만 Python이 해석하도록 할 수 없습니다.제 파일에 문제가 있거나 Python 파서에 문제가 있나요?

이거 드셔보세요

import json

with open('filename.txt', 'r') as f:
    array = json.load(f)

print (array)

문서를 다시 읽어본 결과 세 번째 줄을 다음으로 변경해야 할 것 같습니다.

json_data = json.loads(text)

또는 라인을 삭제합니다.

text = json_file.read()

부터read()파일 인덱스가 파일 끝에 도달합니다(파일 인덱스를 재설정할 수도 있습니다).

python3의 경우 아래 항목만 해당되며 위의 항목은 없습니다.

import json

with open('/emp.json', 'r') as f:

     data=f.read()

print(data)

언급URL : https://stackoverflow.com/questions/38644480/reading-json-file-with-python-3

반응형