질문자 :michele
파일에 이 JSON이 있습니다.
{ "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [ "id": "valore" ], "om_points": "value", "parameters": [ "id": "valore" ] }
모든 JSON 데이터를 인쇄하기 위해 이 스크립트를 작성했습니다.
import json from pprint import pprint with open('data.json') as f: data = json.load(f) pprint(data)
하지만 이 프로그램은 예외를 발생시킵니다:
Traceback (most recent call last): File "<pyshell#1>", line 5, in <module> data = json.load(f) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)
JSON을 구문 분석하고 값을 추출하려면 어떻게 해야 합니까?
데이터가 유효한 JSON 형식이 아닙니다. {}
가 있어야 할 때 []
가 있습니다.
-
[]
는 Python에서 list
라고 하는 JSON 배열을 위한 것입니다. -
{}
는 Python에서 dict
라고 하는 JSON 객체용입니다.
JSON 파일의 모양은 다음과 같습니다.
{ "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": { "id": "valore" }, "om_points": "value", "parameters": { "id": "valore" } }
그런 다음 코드를 사용할 수 있습니다.
import json from pprint import pprint with open('data.json') as f: data = json.load(f) pprint(data)
이제 데이터를 사용하여 다음과 같은 값을 찾을 수도 있습니다.
data["maps"][0]["id"] data["masks"]["id"] data["om_points"]
그것들을 시도하고 그것이 이해되기 시작하는지 확인하십시오.
Justin Peeldata.json
은 다음과 같아야 합니다.
{ "maps":[ {"id":"blabla","iscategorical":"0"}, {"id":"blabla","iscategorical":"0"} ], "masks": {"id":"valore"}, "om_points":"value", "parameters": {"id":"valore"} }
코드는 다음과 같아야 합니다.
import json from pprint import pprint with open('data.json') as data_file: data = json.load(data_file) pprint(data)
with
-statement 에 의존하므로 Python 2.6 이상에서만 작동합니다. Python 2.5 from __future__ import with_statement
, Python <= 2.4에서는 이 답변의 기반이 되는 Justin Peel의 답변을 참조하세요.
이제 다음과 같이 단일 값에 액세스할 수도 있습니다.
data["maps"][0]["id"] # will return 'blabla' data["masks"]["id"] # will return 'valore' data["om_points"] # will return 'value'
BengtJustin Peel의 답변 은 정말 도움이 되지만 Python 3을 사용하는 경우 JSON 읽기를 다음과 같이 수행해야 합니다.
with open('data.json', encoding='utf-8') as data_file: data = json.loads(data_file.read())
참고: json.loads
대신 json.load
. Python 3에서 json.loads
는 문자열 매개변수를 사용합니다. json.load
는 파일과 같은 객체 매개변수를 사용합니다. data_file.read()
는 문자열 객체를 반환합니다.
솔직히 말하면 대부분의 경우 모든 json 데이터를 메모리에 로드하는 것이 문제가 아니라고 생각합니다. JS, Java, Kotlin, cpp에서 이것을 볼 수 있습니다. 제가 사용하는 거의 모든 언어가 녹슬었습니다. 저에게 농담처럼 메모리 문제를 고려하십시오 :)
반면에 json을 모두 읽지 않고는 구문 분석할 수 없다고 생각합니다.
Geng Jiawendata = [] with codecs.open('d:\output.txt','rU','utf-8') as f: for line in f: data.append(json.loads(line))
smbanaei"Ultra JSON" 또는 단순히 "ujson"은 JSON 파일 입력에 []
JSON 요소 목록으로 프로그램에 JSON 입력 파일을 읽는 경우 [{[{}]}, {}, [], etc...]
ujson은 사전 목록, 목록 사전의 임의 순서를 처리할 수 있습니다.
Python 패키지 색인 에서 ujson을 찾을 수 있으며 API는 Python의 내장 json
라이브러리와 거의 동일합니다.
ujson은 더 큰 JSON 파일을 로드하는 경우에도 훨씬 빠릅니다. 제공된 동일한 링크에서 다른 Python JSON 라이브러리와 비교하여 성능 세부 정보를 볼 수 있습니다.
moeabdolPython3을 사용하는 경우 ( connection.json
파일) JSON을 다음과 같이 변경할 수 있습니다.
{ "connection1": { "DSN": "con1", "UID": "abc", "PWD": "1234", "connection_string_python":"test1" } , "connection2": { "DSN": "con2", "UID": "def", "PWD": "1234" } }
그런 다음 다음 코드를 사용합니다.
connection_file = open('connection.json', 'r') conn_string = json.load(connection_file) conn_string['connection1']['connection_string_python']) connection_file.close() >>> test1
sushmit이 구문 분석에는 두 가지 유형이 있습니다.
- 시스템 경로에서 파일의 데이터 구문 분석
- 원격 URL에서 JSON 구문 분석.
파일에서 다음을 사용할 수 있습니다.
import json json = json.loads(open('/path/to/file.json').read()) value = json['key'] print(json['value'])
이 문서에서는 두 가지 시나리오를 사용하여 전체 구문 분석 및 값 가져오기에 대해 설명합니다. Python을 사용하여 JSON 구문 분석
Bibin Wilson여기에서 수정된 data.json
파일로 이동합니다.
{ "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": [{ "id": "valore" }], "om_points": "value", "parameters": [{ "id": "valore" }] }
아래 줄을 사용하여 콘솔에서 데이터를 호출하거나 인쇄할 수 있습니다.
import json from pprint import pprint with open('data.json') as data_file: data_item = json.load(data_file) pprint(data_item)
print(data_item['parameters'][0]['id'])
대한 예상 출력:
{'maps': [{'id': 'blabla', 'iscategorical': '0'}, {'id': 'blabla', 'iscategorical': '0'}], 'masks': [{'id': 'valore'}], 'om_points': 'value', 'parameters': [{'id': 'valore'}]}
print(data_item['parameters'][0]['id'])
대한 예상 출력:
valore
JoboFivepython3 사용자로서 ,
차이 load
및 loads
이 파일에서 JSON 데이터를 읽을 때 특히 방법이 중요하다.
문서에 명시된 대로:
json.load:
이 변환표를 사용하여 fp(JSON 문서를 포함하는 .read() 지원 텍스트 파일 또는 바이너리 파일)를 Python 객체로 역직렬화합니다.
json.loads:
json.loads: 이 변환표를 사용하여 s(JSON 문서를 포함하는 str, bytes 또는 bytearray 인스턴스)를 Python 객체로 역직렬화합니다.
json.load 메소드는 바이너리 파일을 읽을 수 있기 때문에 열린 json 문서를 직접 읽을 수 있습니다.
with open('./recipes.json') as data: all_recipes = json.load(data)
결과적으로 json 데이터는 이 변환표에 따라 지정된 형식으로 사용할 수 있습니다.
https://docs.python.org/3.7/library/json.html#json-to-py-table
muratgozel출처 : http:www.stackoverflow.com/questions/2835559/why-cant-python-parse-this-json-data