https://docs.python.org/3/tutorial/inputoutput.html#saving-structured-data-with-json

json

JSON으로 구조화된 데이터 저장 요약:

  • 직렬화/역직렬화:
    • json.dumps(obj)는 문자열로 변환
    • json.dump(obj, file)는 파일에 바로 씁니다.
      • 다시 복원.
        • json.loads(s)
        • json.load(file)로
import json
x = [1, "simple", "list"]
s = json.dumps(x)        # '[1, "simple", "list"]'
with open("data.json", "w", encoding="utf-8") as f:
	json.dump(x, f)
 
with open("data.json", "r", encoding="utf-8") as f:
	y = json.load(f)     # [1, "simple", "list"]
  • 파일은 UTF-8로 읽고 쓰는 것 권장(특히 JSON 파일은 UTF-8이어야 함).
  • 리스트·딕셔너리 등 기본 타입은 바로 처리 가능.
  • 임의의 사용자 정의 객체는 추가 작업이 필요
    • (직접 dict로 변환하거나 default 매개변수, 커스텀 encoder 사용 등).
  • JSON은 언어 간 호환성이 높아 데이터 교환에 적합.
    참고: pickle은 Python 전용으로 더 복잡한 객체를 직렬화할 수 있지만,
    다른 언어와 호환되지 않고 신뢰할 수 없는 입력을 로드하면 보안 위험이 있습니다.

← python 3.14으로