Python에서는 json module의 json.dumps() Method를 사용하여 dictionary를 JSON 문자열로 변환합니다. 

import json

my_dict = {'a': 1, 'b': 2, 'c': 3}
json_string = json.dumps(my_dict)
print(json_string)

Output :

'{"a": 1, "b": 2, "c": 3}'

json.dump() Method를 사용하여 JSON 문자열을 파일로 저장할 수 있습니다.

with open("data.json", "w") as f:
    json.dump(my_dict, f)

json.dumps() 메서드에는 추가 파라미터를 지정할 수 있습니다. indent, separators, sort_keys 등이 있습니다. 

indent 파라미터는 JSON 문자열을 일반적으로 읽기 쉽게 포맷팅 하는데 사용되고, separators 파라미터는 key-value 사이의 구분자를 지정하는데 사용됩니다. sort_keys 파라미터는 JSON 문자열에서 key를 정렬하는데 사용됩니다.

Decimal, date, time, datetime, timedelta, UUID 등과 같은 특정 타입은 기본적으로 직렬화되지 않습니다. 이러한 타입을 처리하려면 사용자 정의 JSONEncoder를 사용해야 합니다.

반응형