IT기타

[python] json 데이터 읽기

emilyyoo 2025. 3. 3. 19:16
728x90

**python의 json 모듈활용. 

 

import json

# JSON 문자열을 Python 객체로 변환
json.loads('{"name": "John", "age": 30}')  # 문자열 -> dict

# Python 객체를 JSON 문자열로 변환
json.dumps({"name": "John", "age": 30})    # dict -> 문자열

# JSON 파일을 Python 객체로 읽기
with open('file.json', 'r') as f:
    data = json.load(f)                    # 파일 -> dict

# Python 객체를 JSON 파일로 저장
with open('file.json', 'w') as f:
    json.dump(data, f)                     # dict -> 파일

 

 

ex1) .json 파일 읽어서 python 객체에 담기.  

 

try:
    with open(json_file, 'r', encoding='utf-8') as f:
        articles = json.load(f)
except FileNotFoundError:
    print("파일을 찾을 수 없습니다")
except json.JSONDecodeError:
    print("잘못된 JSON 형식입니다")
except MemoryError:
    print("파일이 너무 커서 메모리에 로드할 수 없습니다")

 

==>위의 예시에서 데이터 형태. 

# json_file 파일 내용
[
    {
        "title": "첫 번째 기사 제목",
        "date": "2024-03-02",
        "content": "기사 내용...",
        "url": "https://..."
    },
    {
        "title": "두 번째 기사 제목",
        "date": "2024-03-01",
        "content": "기사 내용...",
        "url": "https://..."
    }
    .............
]

# articles에 담긴(python에서의) 데이터 구조


articles = [
    {
        "title": "첫 번째 기사 제목",
        "date": "2024-03-02",
        "content": "기사 내용...",
        "url": "https://..."
    },
    ...........
]

 

 

ex2) 대용량 파일의 경우 :

 

->  청크(chunk) 단위로 처리

 

def process_large_json(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        # 파일을 한 줄씩 읽어서 처리
        for line in f:
            article = json.loads(line)  # 한 줄씩 JSON 파싱
            # 처리 로직

728x90