programming
json load/loads/dump/dumps 함수
iiliiiili
2021. 11. 23. 10:18
함수 | 사용 | 예 | |
json.load | json 문자열을 python 객체로 변환 | 파일을 읽을 때 | with open('test.json') as json_file: json_data = json.load(json_file) |
json.loads | 문자열을 읽을 때(dict 이 아닌 문자열임 주의) | with open('test.json') as json_file: contents = json_file.read() json_data = json.loads(contents) |
|
json.dump | python 객체를 json 문자열로 변환 | 파이선 객체 -> 스트림 객체(파일) | with open('test.json', 'w') as outfile: json.dump(all_messages, outfile, indent=2, cls=DateTimeEncoder, ensure_ascii=False) |
json.dumps | 파이썬 객체 -> JSON 문자열 | json_string = json.dumps(json_object) print(json_string) |
dump 사용할 때 들여쓰기 사용 - indent (indentation)
ex) json_string = json.dumps(json_object, indent=2)
들여쓰기 2칸