English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON(Java Script Object Notation)은 가벼운, 널리 인정받는 데이터 교환 형식입니다. Python에서 JSON 포맷화 기술을 사용하면 JSON 문자열을 파이썬 객체로 변환하고, 파이썬 객체를 JSON 문자열로 변환할 수 있습니다.
이 기능을 사용하려면 Python의 json 모듈을 사용해야 합니다. json 모듈은 Python 표준 라이브러리에 포함되어 있습니다. 따라서 먼저 그를 임포트해야 합니다.
import json
json 모듈에서는 dump()와 dumps()와 같은 메서드들이 파이썬 객체를 JSON 문자열로 변환할 수 있습니다. dump() 메서드는 두 가지 매개변수를 가집니다. 첫 번째는 객체이며, 두 번째는 파일 객체입니다. 이 메서드는 객체를 JSON 형식으로 변환합니다.스트림시리얼라이즈하여 파일 객체로 변환합니다. 마찬가지로, dumps() 메서드는 단 하나의 매개변수를 받습니다. 매개변수는 객체입니다. 이 메서드는 객체를 JSON으로 변환합니다.문자열.
import json from io import StringIO str_io_obj = StringIO() #Use JSON Dump to make StringIO json.dump(["India", "Australia", "Brazil"], str_io_obj) print('StringIO Object value: ') + str(str_io_obj.getvalue()) my_json = { "name": "Kalyan", "age": 25, "city": "Delhi" } print(json.dumps(my_json, indent=4))
출력 결과
StringIO Object value: ["India", "Australia", "Brazil"] { "name": "Kalyan", "age": 25, "city": "Delhi" }
이 경우, 우리는 JSON 문자열을 역시리얼라이즈할 것입니다. 두 가지 다른 방법이 있습니다. 이들은 load()와 load()입니다. 이 두 가지 방법 모두 JSON 파일을 매개변수로 받습니다. load()는 파일 객체 데이터를 파이썬 객체로 변환하며, load()는 문자열 타입 데이터를 변환합니다.
import json from io import StringIO str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]')} #load from StringIO print('Load: ' + str(json.load(str_io_obj))) print('String to Json: ' + str(json.loads('{"xyz" : 1, "abc" : 2, "xyz" : 3, "pqr" : 4}')))
출력 결과
Load: ['xyz', 'abc', 'xyz', 'pqr'] String to Json: {'xyz': 3, 'abc': 2, 'pqr': 4}
JSONEncoder 클래스는 Python 객체를 JSON 형식으로 변환하는 데 사용됩니다. 이 예제에서는 JSONEncoder를 사용하여 복잡한 객체를 JSON 타입 객체로 변환하는 방법을 보여줍니다.
import json class Comp_Encoder(json.JSONEncoder): def default(self, comp_obj): if isinstance(comp_obj, complex): return [comp_obj.real, comp_obj.imag] return json.JSONEncoder.default(self, comp_obj) print(json.dumps(5+8j, cls=Comp_Encoder))
출력 결과
[5.0, 8.0]
JSONDecoder 클래스는 반대의 작업을 수행합니다.
import json my_str = '{"Asim" : 25, "Priyesh" : 23, "Asim" : "28"" #Decode JSON using the JSONDecoder print(json.JSONDecoder().decode(my_str)) print(json.JSONDecoder().raw_decode(my_str))
출력 결과
{'Asim': '28', 'Priyesh': 23} ({'Asim': '28', 'Priyesh': 23}, 44)