**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 파싱
# 처리 로직
'IT기타' 카테고리의 다른 글
이미지 파일 여러개를 하나의 이미지로 만들기 (0) | 2025.03.12 |
---|---|
가상환경 보기 및 활성화 (0) | 2025.03.09 |
로지텍 페블 무선 마우스 <-> 갤럭시탭, 맥북 연결 (1) | 2025.03.03 |
(React)데이터 로딩 상태를 표시하는 방법 (0) | 2025.02.24 |
Next.js 프로젝트 시작하기 (0) | 2025.02.23 |