Programming Language/Python

Python의 JSON 모듈 사용하기

niconicon 2024. 1. 14. 23:39

 

Python에서 JSON 데이터를 다루는 방법은 매우 중요한 주제입니다. 이 글에서는 Python의 json 모듈을 사용하여 JSON 데이터를 읽고, 쓰고, 파싱 하는 방법을 자세히 알아보겠습니다. JSON(JavaScript Object Notation)은 데이터를 저장하거나 전송할 때 사용되는 경량의 데이터 포맷입니다. 웹 개발에서 흔히 사용되며, Python과 같은 다양한 프로그래밍 언어에서 쉽게 사용할 수 있습니다.

 

1. JSON 모듈 소개

1) JSON이란?

JSON은 "JavaScript Object Notation"의 약자로, 데이터를 저장하거나 전송할 때 사용되는 경량의 텍스트 기반 포맷입니다. 이 포맷은 사람이 읽고 쓰기 쉬우며, 기계가 파싱하고 생성하기에도 적합합니다.

2) Python에서의 JSON

Python에서는 json 모듈을 통해 JSON 데이터를 쉽게 다룰 수 있습니다. 이 모듈은 JSON 문자열과 Python 데이터 타입 간의 변환을 지원합니다.

 

2. JSON 데이터 읽기와 쓰기

1) JSON 데이터 읽기

JSON 데이터를 읽는 것은 json.load() 함수를 사용하여 파일에서 직접 읽거나 문자열로부터 JSON 데이터를 Python 데이터 타임으로 변환할 수 있습니다.

(1) 파일에서 JSON 데이터 읽기

import json

with open('example.json', 'r') as file:
    data = json.load(file)
    print(data)

(2) 문자열에서 JSON 데이터 읽기

import json

json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data)

2) JSON 데이터 쓰기

JSON 데이터를 쓰는 것은 Python 데이터 타입을 JSON 문자열로 변환하는 과정을 포함합니다. 이는 json.dump() 함수를 사용하여 파일에 직접 쓰거나 문자열을 생성 할 수 있습니다.

(1) 파일에 JSON 데이터 쓰기

import json

data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

with open('output.json', 'w') as file:
    json.dump(data, file)

(2) JSON 문자열 생성하기

import json

data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

json_string = json.dumps(data)
print(json_string)

 

3. 고급 JSON 처리

1) JSON 데이터의 예쁘게 출력하기

json.dumps() 함수는 indent 파라미터를 사용하여 JSON 데이터를 예쁘게 출력할 수 있습니다.

import json

data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

pretty_json = json.dumps(data, indent=4)
print(pretty_json)

2) 커스텀 JSON 인코더/디코더 사용하기

Python의 json 모듈은 커스텀 인코더와 디코더를 정의하여 특정 Python 객체를 JSON으로 변환하거나, JSON을 Python 객체로 변환하는 기능을 제공합니다.

(1) 커스텀 JSON 인코더

import json
from datetime import datetime

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj)

# datetime 객체를 JSON으로 변환
now = datetime.now()
json_string = json.dumps(now, cls=CustomEncoder)
print(json_string)

이 코드는 datetime 객체를 ISO 포맷의 문자열로 변환하여 JSON으로 인코딩합니다.

(2) 커스텀 JSON 디코더

import json
from datetime import datetime

def custom_decoder(obj):
    if 'datetime' in obj:
        return datetime.strptime(obj['datetime'], "%Y-%m-%dT%H:%M:%S.%f")
    return obj

json_string = '{"datetime": "2024-01-14T12:34:56.789000"}'
data = json.loads(json_string, object_hook=custom_decoder)
print(data)

이 코드는 JSON 문자열에 포함된 특정 포맷의 날짜/시간 문자열을 datetime 객체로 변환합니다.

 

4. 마무리

Python의 json 모듈을 사용하면 JSON 데이터를 쉽게 다룰 수 있습니다. 파일이나 문자열에서 JSON 데이터를 읽고, Python 객체를 JSON으로 변환하는 기능은 데이터를 처리하고 저장하는 데 있어 매우 유용합니다. 또한, 커스텀 인코더와 디코더를 사용하여 더 복잡한 데이터 타입도 쉽게 처리할 수 있습니다. 이처럼 Python의 json 모듈은 데이터 교환과 저장 과정에서 필수적인 도구입니다.