본문 바로가기
목차
Python

Python에서 JSON 다루기-json모듈

by ds31x 2025. 8. 6.
728x90
반응형

https://www.delftstack.com/ko/howto/python/write-json-to-file-in-python/

1. JSON이란?

JSON (JavaScript Object Notation)은 경량의 데이터 교환 형식.

데이터 교환 형식은 다른 이름으로 Serialized Data라고도 불리며, JSON은 그 중에서 Text Serialization 방식. 

JavaScript에서 시작되었지만 현재는 다양한 프로그래밍 언어에서 널리 사용되고 있음.

 

JSON에 대한 보다 자세한 내용은 다음을 참고.

2024.01.07 - [분류 전체보기] - [Term] JSON (JavaScript Object Notation) :

 

[Term] JSON (JavaScript Object Notation) :

JSON (JavaScript Object Notation)은JavaScript에서 Object Notation (객체 표기)의 목적으로 제안되었고,JavaScript 언어의 subset 임.하지만, 오늘날 JSON은 프로그램들 간에 데이터를 교환에 사용되는 대표적인 Light-

ds31x.tistory.com


JSON vs Python 문법 비교

Python JSON Desc.
None null 빈 값
True/False true/false 불린 값
'문자열' 또는 "문자열" "문자열" 문자열 (JSON은 반드시 쌍따옴표)
[1, 2, 3,] [1, 2, 3] 배열 (JSON은 마지막 콤마 불허)

2. json 모듈 기본 함수들

Python의 json 모듈은 4개의 주요 함수를 제공:

import json

# 메모리 와 JSON 문자열
json.dumps()  # Python 객체 를 JSON 문자열 로
json.loads()  # JSON 문자열 을 Python 객체 로

# 파일 과 JSON
json.dump()   # Python 객체 를 JSON 파일 로
json.load()   # JSON 파일 을 Python 객체 로
  • dumps = dump string (문자열로 덤프)
  • loads = load string (문자열에서 로드)
  • dump = 파일로 덤프
  • load = 파일에서 로드

3. JSON 함수들의 매개변수와 반환값

3-1. json.dumps() 함수: object ▷ string

함수 시그니처:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, 
           allow_nan=True, cls=None, indent=None, separators=None, 
           default=None, sort_keys=False)

주요 매개변수:

  • obj: 직렬화할 Python 객체 (필수)
  • indent: 들여쓰기 스페이스 수 (int) 또는 문자열
  • ensure_ascii: ascii 문자만 사용할지 여부 (bool, 기본값 True)
    • 호환성을 고려하여 True 이고 ascii외의 문자는 utf-8의 escape sequence로 표기됨.
  • sort_keys: 딕셔너리 키를 정렬할지 여부 (bool, 기본값 False)
  • default: 직렬화 불가능한 객체 처리 함수
  • cls : JSONEncoder를 상속한 Custom Class로 직렬화 불가능한 객체를 클래스로 처리위해 지정 (기본값 Null)
  • separators: (item_separator, key_separator) 튜플
  • skipkeys: 기본 타입이 아닌 키 건너뛸지 여부 (bool, 기본값 False)
    • False인 경우, 직렬화가 불가능한 키가 있을 경우 TypeError발생.

반환값:

  • JSON 형식의 문자열 (str)

예시:

import json

data = {"name": "김철수", "age": 30}

# 기본 사용
result = json.dumps(data)  # '{"name": "\\uae40\\ucca0\\uc218", "age": 30}'

# 옵션 사용
result = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)

3-2. json.loads() 함수: string ▷ object

함수 시그니처:

json.loads(s, *, cls=None, object_hook=None, parse_float=None, 
           parse_int=None, parse_constant=None, object_pairs_hook=None)

주요 매개변수:

  • s: JSON 문자열 (str, bytes, bytearray 타입)
  • object_hook: 디코딩된 객체를 변환하는 함수
  • parse_float: float 파싱 함수 (기본값: float)
  • parse_int: int 파싱 함수 (기본값: int)
  • parse_constant: 상수(-Infinity, Infinity, NaN) 파싱 함수

반환값:

  • Python 객체 ( dict, list, str, int, float, bool, None 로 구성된 collection 타입)
  • 주로 dict 아니면 list 객체임.

예시:

import json
from decimal import Decimal

json_str = '{"price": 19.99, "quantity": 5}'

# 기본 사용
data = json.loads(json_str)  # {'price': 19.99, 'quantity': 5}

# Decimal로 float 파싱
data = json.loads(json_str, parse_float=Decimal)  
# data = {'price': Decimal('19.99'), 'quantity': 5}

3-3. json.dump() 함수: object ▷ file

함수 시그니처:

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
          allow_nan=True, cls=None, indent=None, separators=None, 
          default=None, sort_keys=False)

주요 매개변수:

  • obj: 직렬화할 Python 객체 (필수)
  • fp: 쓰기 가능한 파일 객체 (필수)
  • cls: 사용할 JSONEncoder 서브클래스 (기본값 None)
  • 나머지 매개변수는 json.dumps()와 동일

반환값:

  • None (파일에 직접 쓰기)

예시:

import json

data = {"users": [{"name": "김철수", "id": 1}, {"name": "이영희", "id": 2}]}

# 파일에 JSON 저장
with open('users.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

3-4. json.load() 함수: file ▷ object

함수 시그니처:

json.load(fp, *, cls=None, object_hook=None, parse_float=None,
          parse_int=None, parse_constant=None, object_pairs_hook=None)

주요 매개변수:

  • fp: 읽기 가능한 파일 객체 (필수)
  • cls: 사용할 JSONDecoder 서브클래스 (기본값 None)
  • 나머지 매개변수는 json.loads()와 동일

반환값:

  • Python 객체 ( dict, list, str, int, float, bool, None)
  • 주로 dict 아니면 list 객체임.

예시:

import json

# JSON 파일 읽기
with open('users.json', 'r', encoding='utf-8') as file:
    data = json.load(file)  # Python 객체로 반환

4. Python 데이터를 JSON으로 변환 (Serialization)

2025.08.06 - [CE] - [Term] Serialization-Data Exchnaged Format

 

[Term] Serialization-Data Exchnaged Format

Serialization의 일반적 의미메모리 객체 및 데이터를저장/전송 가능한 형태로변환하는 일반적인 개념메모리의 객체/데이터 구조를 "저장/전송 가능한 형태"로 변환하는 과정컴퓨터 메모리에 흩어

ds31x.tistory.com


4-1. 기본 변환 - json.dumps()

import json

# Python 딕셔너리
person_data = {
    "name": "김철수",
    "age": 30,
    "is_student": False,
    "car": None,
    "hobbies": ["독서", "영화감상", "운동"],
    "address": {
        "city": "서울",
        "district": "강남구"
    }
}

# JSON 문자열로 변환
json_string = json.dumps(person_data)
print(json_string)
print(type(json_string))  # <class 'str'>

출력:

{"name": "\uae40\ucca0\uc218", "age": 30, "is_student": false, "car": null, "hobbies": ["\ub3c5\uc11c", "\uc601\ud654\uac10\uc0c1", "\uc6b4\ub3d9"], "address": {"city": "\uc11c\uc6b8", "district": "\uac15\ub0a8\uad6c"}}

4-2. 가독성 향상 옵션

# 들여쓰기와 한글 표시
json_string = json.dumps(person_data, 
                        indent=2,           # 2칸 들여쓰기
                        ensure_ascii=False) # 한글 유지

print(json_string)

출력:

{
  "name": "김철수",
  "age": 30,
  "is_student": false,
  "car": null,
  "hobbies": [
    "독서",
    "영화감상",
    "운동"
  ],
  "address": {
    "city": "서울",
    "district": "강남구"
  }
}

4-3. 키 정렬

# 키를 알파벳 순으로 정렬
json_string = json.dumps(person_data, 
                        indent=2,
                        ensure_ascii=False,
                        sort_keys=True)
print(json_string)

5. JSON을 Python 데이터로 변환 (Deserialization)

serialization의 반대가 desirialization임.


5-1 .기본 변환 - json.loads()

import json

# JSON 문자열
json_string = '''
{
  "name": "김철수",
  "age": 30,
  "is_student": false,
  "car": null,
  "hobbies": ["독서", "영화감상"],
  "address": {
    "city": "서울",
    "district": "강남구"
  }
}
'''

# Python 객체로 변환
python_data = json.loads(json_string)
print(python_data)
print(type(python_data))  # <class 'dict'>

# 데이터 접근
print(f"이름: {python_data['name']}")
print(f"나이: {python_data['age']}")
print(f"나이: {python_data['is_student']}")
print(f"취미: {', '.join(python_data['hobbies'])}")
  • true / false 의 변화를 주의할 것.

6. 파일과 JSON 작업

6-1. JSON 파일에 쓰기 - json.dump()

import json

# 데이터 준비
students = [
    {"name": "김철수", "age": 20, "grade": "A"},
    {"name": "이영희", "age": 19, "grade": "B+"},
    {"name": "박민수", "age": 21, "grade": "A-"}
]

# JSON 파일로 저장
with open('students.json', 'w', encoding='utf-8') as file:
    json.dump(students, file, 
             indent=2, 
             ensure_ascii=False)

print("students.json 파일이 생성되었습니다.")

6-2. JSON 파일에서 읽기 - json.load()

import json

# JSON 파일 읽기
try:
    with open('students.json', 'r', encoding='utf-8') as file:
        loaded_students = json.load(file)

    print("불러온 데이터:")
    for student in loaded_students:
        print(f"이름: {student['name']}, 나이: {student['age']}, 성적: {student['grade']}")

except FileNotFoundError:
    print("파일을 찾을 수 없습니다.")

7. JSON으로 변환 가능한 데이터 타입

7-1. 지원되는 타입

import json

# 지원되는 Python 타입들
supported_data = {
    "문자열": "hello",
    "정수": 42,
    "실수": 3.14,
    "불린": True,
    "널값": None,
    "리스트": [1, 2, 3],
    "딕셔너리": {"key": "value"}
}

json_result = json.dumps(supported_data, indent=2, ensure_ascii=False)
print(json_result)

7-2. 지원되지 않는 타입과 해결방법

import json
from datetime import datetime, date

# 문제가 되는 데이터
problematic_data = {
    "today": datetime.now(),
    "birth_date": date(1990, 5, 15),
    "complex_number": 3+4j,
    "user_set": {"admin", "user", "guest"}
}

# 이 데이터를 그대로 json.dumps()하면 TypeError 발생
# TypeError: Object of type datetime is not JSON serializable

# 해결방법 1: default 매개변수 사용
def json_serializer(obj):
    """JSON으로 직렬화할 수 없는 객체들을 처리"""
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    elif isinstance(obj, complex):
        return {"__complex__": True, "real": obj.real, "imag": obj.imag}
    elif isinstance(obj, set):
        return {"__set__": True, "items": list(obj)}
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")

# 직렬화
json_result = json.dumps(problematic_data, 
                        default=json_serializer, 
                        indent=2, 
                        ensure_ascii=False)
print("방법 1 - default 함수 사용:")
print(json_result)

# 해결방법 2: cls 매개변수로 커스텀 인코더/디코더 사용
class ExtendedJSONEncoder(json.JSONEncoder):
    """확장된 JSON 인코더"""
    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return {"__datetime__": obj.isoformat(), "__type__": type(obj).__name__}
        elif isinstance(obj, complex):
            return {"__complex__": True, "real": obj.real, "imag": obj.imag}
        elif isinstance(obj, set):
            return {"__set__": True, "items": sorted(list(obj))}  # 정렬로 일관성 보장
        return super().default(obj)

class ExtendedJSONDecoder(json.JSONDecoder):
    """확장된 JSON 디코더"""
    def __init__(self, *args, **kwargs):
        super().__init__(object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, dct):
        if "__datetime__" in dct:
            dt_str = dct["__datetime__"]
            if dct["__type__"] == "datetime":
                return datetime.fromisoformat(dt_str)
            elif dct["__type__"] == "date":
                return datetime.fromisoformat(dt_str).date()
        elif "__complex__" in dct:
            return complex(dct["real"], dct["imag"])
        elif "__set__" in dct:
            return set(dct["items"])
        return dct

# cls 방법으로 직렬화/역직렬화
json_result_cls = json.dumps(problematic_data, 
                            cls=ExtendedJSONEncoder,
                            indent=2, 
                            ensure_ascii=False)
print("\n방법 2 - cls 매개변수 사용:")
print(json_result_cls)

# cls 방법으로 역직렬화
restored_data_cls = json.loads(json_result_cls, cls=ExtendedJSONDecoder)
print("\n복원된 데이터 (cls 방법):")
print(f"오늘 날짜 타입: {type(restored_data_cls['today'])}")
print(f"생일 타입: {type(restored_data_cls['birth_date'])}")
print(f"복소수 타입: {type(restored_data_cls['complex_number'])}")
print(f"집합 타입: {type(restored_data_cls['user_set'])}")

# 해결방법 3: object_hook 함수 사용 (역직렬화에서만 가능)
def json_deserializer(dct):
    """JSON에서 복원할 때 특수 객체들을 원래 타입으로 변환"""
    if "__complex__" in dct:
        return complex(dct["real"], dct["imag"])
    elif "__set__" in dct:
        return set(dct["items"])
    # 날짜 문자열 자동 감지 및 변환
    for key, value in dct.items():
        if isinstance(value, str) and key.endswith('_date'):
            try:
                dct[key] = datetime.fromisoformat(value).date()
            except ValueError:
                pass
        elif isinstance(value, str) and 'today' in key:
            try:
                dct[key] = datetime.fromisoformat(value)
            except ValueError:
                pass
    return dct

# object_hook 방법으로 역직렬화
restored_data_hook = json.loads(json_result, object_hook=json_deserializer)
print("\n복원된 데이터 (object_hook 방법):")
print(f"오늘 날짜 타입: {type(restored_data_hook['today'])}")
print(f"생일 타입: {type(restored_data_hook['birth_date'])}")
print(f"복소수 타입: {type(restored_data_hook['complex_number'])}")
print(f"집합 타입: {type(restored_data_hook['user_set'])}")

출력:

{방법 1 - default 함수 사용:
{
  "today": "2024-01-15T14:30:45.123456",
  "birth_date": "1990-05-15",
  "complex_number": {
    "__complex__": true,
    "real": 3.0,
    "imag": 4.0
  },
  "user_set": {
    "__set__": true,
    "items": ["admin", "user", "guest"]
  }
}

방법 2 - cls 매개변수 사용:
{
  "today": {
    "__datetime__": "2024-01-15T14:30:45.123456",
    "__type__": "datetime"
  },
  "birth_date": {
    "__datetime__": "1990-05-15",
    "__type__": "date"
  },
  "complex_number": {
    "__complex__": true,
    "real": 3.0,
    "imag": 4.0
  },
  "user_set": {
    "__set__": true,
    "items": ["admin", "guest", "user"]
  }
}

복원된 데이터 (cls 방법):
오늘 날짜 타입: <class 'datetime.datetime'>
생일 타입: <class 'datetime.date'>
복소수 타입: <class 'complex'>
집합 타입: <class 'set'>

7-3. 각 방법의 장단점 비교

방법 장점 단점 적합한 상황
default 함수 - 간단하고 직관적
- 빠른 구현
- 복잡한 로직 처리 어려움
- 타입별 세밀한 제어 제한
간단한 변환, 일회성 처리
cls (커스텀 클래스) - 완전한 제어 가능
- 재사용성 좋음
- 복잡한 로직 구현 가능
- 코드량 많음
- 클래스 이해 필요
복잡한 데이터 구조, 반복 사용
object_hook - 역직렬화만 필요할 때 유용
- 유연한 패턴 매칭
- 직렬화는 별도 처리 필요 외부 JSON 읽기, 선택적 변환

7-4 간편한 해결책: 문자열 변환

복잡한 타입 복원이 필요하지 않다면, 단순히 문자열로 변환하는 방법도 있음:

import json
from datetime import datetime

# 간단한 default 함수
def simple_serializer(obj):
    """모든 비표준 객체를 문자열로 변환"""
    return str(obj)

data = {
    "timestamp": datetime.now(),
    "user_data": {"name": "김철수", "roles": {"admin", "user"}}
}

# 문자열로 변환
json_str = json.dumps(data, default=simple_serializer, indent=2, ensure_ascii=False)
print(json_str)
  • 단순하지만, 꽤 많이 사용됨.
  • 단, 이 방법은 원래 타입으로 복원할 수 없음.

8. 에러 처리

8-1. 일반적인 JSON 에러들

  • 작은따옴표 사용: JSON은 반드시 쌍따옴표(double quotes) 사용 필요
  • 마지막 콤마: JSON은 trailing comma 허용하지 않음
  • 값에 따옴표 누락: 문자열 값은 반드시 따옴표로 감싸야 함
  • 콤마 누락: 키-값 쌍 사이에 콤마 필수
  • 중괄호/대괄호 불일치: 여는 괄호와 닫는 괄호의 개수 불일치

8-2. JSONDecodeError의 유용한 속성

  • msg: 구체적인 오류 메시지 제공
  • pos: 오류가 발생한 문자의 위치(position) 정보 제공
  • 디버깅 시 오류 위치 빠른 파악 가능

8-3. Example Code

import json

def handle_json_errors():
    """자주 발생하는 JSON 에러들과 처리 방법"""

    # 잘못된 JSON 예시들
    invalid_jsons = [
        ("작은따옴표 사용", "{'name': 'John'}"),
        ("마지막 콤마", '{"name": "John",}'),
        ("값에 따옴표 없음", '{"name": John}'),
        ("콤마 누락", '{"name": "John" "age": 30}'),
        ("중괄호 미완성", '{"name": "John"'),
        ("빈 문자열", ""),
    ]

    for description, invalid_json in invalid_jsons:
        print(f"\n{description}: {invalid_json}")
        try:
            result = json.loads(invalid_json)
            print(f"성공: {result}")
        except json.JSONDecodeError as e:
            print(f"   에러 메시지: {e.msg}")
            print(f"   에러 위치:  {e.pos}번째 문자")

# 실행
handle_json_errors()

출력 예시:

작은따옴표 사용: {'name': 'John'}
   에러 메시지: Expecting property name enclosed in double quotes
   에러 위치: 1번째 문자

마지막 콤마: {"name": "John",}
   에러 메시지: Expecting property name enclosed in double quotes  
   에러 위치: 16번째 문자

# Omit

8-4. 파싱에러에 대비한 JSON 처리

  • JSON 파싱 실패로 인한 프로그램 중단 방지
  • 예외 상황에서도 서비스 연속성(service continuity) 보장
  • 기본값(default value) 반환을 통한 우아한 실패(graceful failure) 처리
  • 사용자 경험(user experience) 향상
import json

def safe_json_parse(json_string, default=None):
    """안전한 JSON 파싱 함수"""
    try:
        return json.loads(json_string)
    except json.JSONDecodeError as e:
        print(f"JSON 파싱 실패: {e}")
        return default
    except Exception as e:
        print(f"예상치 못한 에러: {e}")
        return default

# 사용 예시
test_cases = [
    '{"name": "김철수", "age": 30}',  # 정상
    '{"name": "John",}',              # 잘못된 형식
    '',                               # 빈 문자열
]

for test_json in test_cases:
    result = safe_json_parse(test_json, default={})
    print(f"입력: {test_json} → 결과: {result}")

8-5 .JSON 파일 처리시 에러 처리

파싱 에러 외에도 다음의 에러가 발생 가능함.

  • FileNotFoundError: 파일 부재 상황
  • PermissionError: 파일 접근 권한 부족
  • JSONDecodeError: JSON 형식 오류
  • UnicodeDecodeError: 인코딩(encoding) 문제
  • TypeError: 직렬화 불가능한 객체 포함
import json

def load_json_file(filepath):
    """JSON 파일 안전하게 읽기"""
    try:
        with open(filepath, 'r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        print(f"파일을 찾을 수 없습니다: {filepath}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON 파일 형식 오류: {e}")
        return None
    except Exception as e:
        print(f"파일 읽기 에러: {e}")
        return None

def save_json_file(data, filepath):
    """JSON 파일 안전하게 저장"""
    try:
        with open(filepath, 'w', encoding='utf-8') as file:
            json.dump(data, file, indent=2, ensure_ascii=False)
        return True
    except TypeError as e:
        print(f"직렬화할 수 없는 데이터: {e}")
        return False
    except Exception as e:
        print(f"파일 저장 에러: {e}")
        return False

# 사용 예시
data = {"name": "김철수", "age": 30}

# 저장
if save_json_file(data, "user.json"):
    print("파일 저장 성공")

# 읽기
loaded_data = load_json_file("user.json")
if loaded_data:
    print(f"파일 읽기 성공: {loaded_data}")

에러에 강건한 JSON처리를 위해서 다음의 원칙을 준수할 것.

  • 예외 타입별 개별 처리: 구체적인 원인 파악 가능
  • UTF-8 인코딩 명시: 한글 및 특수문자 처리 문제 방지
  • 적절한 반환값 설정: None 또는 boolean을 통한 성공/실패 표시

8-6. Core Error Handling Principles

  1. JSONDecodeError 우선 처리
    • JSON 형식 오류 전용 예외 클래스 활용
    • 구체적인 오류 정보(msg, pos) 활용을 통한 디버깅 효율성 향상
  2. 기본값 제공 (Default Value Provision)
    • 에러 발생시 적절한 대체값 반환
    • 프로그램 중단 방지를 통한 안정성 확보
  3. 명확한 에러 메시지 (Clear Error Messages)
    • 개발자 및 사용자를 위한 구체적인 오류 정보 제공
    • 디버깅 과정의 효율성 향상
  4. 파일 인코딩 명시 (Explicit File Encoding)
    • UTF-8 인코딩 명시적 지정
    • 한글 및 특수문자 처리 문제 예방
  5. 예외 구분 처리 (Exception Type Differentiation)
    • 파일 시스템 오류와 JSON 파싱 오류의 분리 처리
    • 직렬화 오류(TypeError)의 별도 처리

9. 실전 활용 예제 (작성중)

9-1 설정 파일 관리

import json
import os

class ConfigManager:
    def __init__(self, config_file='config.json'):
        self.config_file = config_file
        self.config = self.load_config()

    def load_config(self):
        """설정 파일 로드"""
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r', encoding='utf-8') as file:
                return json.load(file)
        else:
            return self.get_default_config()

    def get_default_config(self):
        """기본 설정 반환"""
        return {
            "database": {
                "host": "localhost",
                "port": 5432,
                "name": "myapp"
            },
            "logging": {
                "level": "INFO",
                "file": "app.log"
            },
            "features": {
                "debug_mode": False,
                "cache_enabled": True
            }
        }

    def save_config(self):
        """설정 파일 저장"""
        with open(self.config_file, 'w', encoding='utf-8') as file:
            json.dump(self.config, file, indent=2, ensure_ascii=False)

    def get(self, key, default=None):
        """설정값 가져오기"""
        keys = key.split('.')
        value = self.config
        for k in keys:
            value = value.get(k, default)
            if value is None:
                return default
        return value

    def set(self, key, value):
        """설정값 설정하기"""
        keys = key.split('.')
        config = self.config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
        self.save_config()

# 사용 예시
config = ConfigManager()
print(f"데이터베이스 호스트: {config.get('database.host')}")
config.set('features.debug_mode', True)
print(f"디버그 모드: {config.get('features.debug_mode')}")

9-2 API 응답 처리

import json
from typing import Dict, Any, Optional

class APIResponseHandler:
    @staticmethod
    def parse_response(response_text: str) -> Optional[Dict[str, Any]]:
        """API 응답 파싱"""
        try:
            return json.loads(response_text)
        except json.JSONDecodeError:
            print("유효하지 않은 JSON 응답")
            return None

    @staticmethod
    def extract_user_info(api_response: str) -> Dict[str, Any]:
        """사용자 정보 추출"""
        data = APIResponseHandler.parse_response(api_response)

        if not data:
            return {}

        return {
            "id": data.get("id"),
            "name": data.get("name", "Unknown"),
            "email": data.get("email"),
            "profile_image": data.get("profile", {}).get("image_url"),
            "last_login": data.get("metadata", {}).get("last_login")
        }

# 예시 API 응답
sample_api_response = '''
{
  "id": 12345,
  "name": "김개발",
  "email": "kim@example.com",
  "profile": {
    "image_url": "https://example.com/profile.jpg",
    "bio": "파이썬 개발자"
  },
  "metadata": {
    "last_login": "2024-01-15T10:30:00Z",
    "signup_date": "2023-06-01"
  }
}
'''

handler = APIResponseHandler()
user_info = handler.extract_user_info(sample_api_response)
print("추출된 사용자 정보:")
for key, value in user_info.items():
    print(f"  {key}: {value}")

같이 보면 좋은 자료들

2025.08.06 - [CE] - [Term] Serialization-Data Exchnaged Format

 

[Term] Serialization-Data Exchnaged Format

Serialization의 일반적 의미메모리 객체 및 데이터를저장/전송 가능한 형태로변환하는 일반적인 개념메모리의 객체/데이터 구조를 "저장/전송 가능한 형태"로 변환하는 과정컴퓨터 메모리에 흩어

ds31x.tistory.com

2024.01.07 - [분류 전체보기] - [Term] JSON (JavaScript Object Notation) :

 

[Term] JSON (JavaScript Object Notation) :

JSON (JavaScript Object Notation)은JavaScript에서 Object Notation (객체 표기)의 목적으로 제안되었고,JavaScript 언어의 subset 임.하지만, 오늘날 JSON은 프로그램들 간에 데이터를 교환에 사용되는 대표적인 Light-

ds31x.tistory.com

 

728x90