Day 17: JSON 처리
JSON이란?
JavaScript Object Notation의 약자로, 데이터 교환에 널리 사용되는 텍스트 형식입니다.
Python 객체 ↔ JSON 변환
import json
# Python -> JSON 문자열
data = {
"name": "철수",
"age": 25,
"hobbies": ["코딩", "독서"],
"address": {"city": "서울", "zip": "06000"}
}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# JSON 문자열 -> Python
parsed = json.loads(json_str)
print(parsed["name"]) # 철수
print(parsed["hobbies"][0]) # 코딩
타입 매핑
| Python | JSON |
|---|---|
dict | object {} |
list | array [] |
str | string |
int, float | number |
True / False | true / false |
None | null |
JSON 파일 읽기/쓰기
# 파일로 저장
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 파일에서 읽기
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["address"]["city"]) # 서울
복잡한 JSON 다루기
# API 응답 예시
api_response = """
{
"status": "success",
"results": [
{"id": 1, "title": "Python 입문", "price": 25000},
{"id": 2, "title": "Django 실전", "price": 35000},
{"id": 3, "title": "FastAPI 가이드", "price": 30000}
]
}
"""
data = json.loads(api_response)
for book in data["results"]:
print(f"{book['title']}: {book['price']:,}원")
# 필터링과 정렬
expensive = sorted(
[b for b in data["results"] if b["price"] >= 30000],
key=lambda b: b["price"],
reverse=True
)
오늘의 연습문제
- 설정 파일(config.json)을 읽어 프로그램에 적용하는 코드를 작성하세요.
- 리스트 데이터를 JSON 파일로 저장하고 다시 읽어오는 CRUD 함수를 만드세요.
- 중첩된 JSON에서 특정 키의 값을 재귀적으로 찾는 함수를 작성하세요.