
JSON serialize는 일반적으로 Python의 json 모듈을 사용하여 데이터를 JSON 형식으로 변환합니다. serialize할 수 있는 데이터 타입은 다음과 같습니다.
- 문자열(str)
- 정수(int)
- 실수(float)
- 불리언(boolean)
- 리스트(list)
- 튜플(tuple)
- 사전(dict)
그러나, datetime 객체는 기본적으로 serialize되지 않습니다. datetime 객체를 serialize할 때는 다음과 같은 방법을 사용할 수 있습니다.
- datetime 객체를 문자열로 변환하여 serialize
- datetime 객체를 serialize할 때, custom encoder를 사용하여 serialize
예를 들어, datetime 객체를 문자열로 변환하여 serialize할 때는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
python
import json
from datetime import datetime
data = {'date': datetime.now()}
data_str = json.dumps(data, default=lambda x: x.isoformat())
print(data_str)
또한, serialize을 사용하여 데이터를 JSON 형식으로 변환할 때, pretty print 옵션을 사용하여 JSON 형식으로 변환할 때는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
python
import json
data = {'name': 'John', 'age': 30}
data_str = json.dumps(data, indent=4)
print(data_str)
pretty print 옵션을 사용하여 JSON 형식으로 변환할 때, indent 옵션을 사용하여 JSON 형식의 들여쓰기를 조절할 수 있습니다. indent 옵션을 사용하지 않으면, JSON 형식은 한 줄로 출력됩니다.
2025-07-20 14:54