티스토리 뷰
1. json 파일 읽고 쓰기
1) 읽기
대상 json
[
{"id": "this is id",
"category": "this is category",
"media_type": "this is media_type",
"media_sub_type": "this is media_sub_type",
"media_name": "this is media_name",
"size": "this is size",
"char_count": "this is char_count",
"publish_date": "this is publish_date",
"title": "this is title"}
]
읽기
import json
with open("target.json", "r", encoding="utf-8") as f:
taget_json = json.load(f)
print(len(target_json)) # list의 길이 1 출력
for i in range(len(target_json)):
print(target_json[i]["id"]) # "this is id" 출력
print(target_json[i]["title"]) # "this is title" 출력
2) 쓰기
import json
my_data = [{"id": "this is id", "title": "this is title"}]
with open("my_prac.json", "w", encoding="utf-8") as f: # 쓰기 모드(w)나 추가 모드(a)로 열기
json.dump(my_data, f) #json.dump를 이용하여 쓰기
쓰기 결과 json
[
{"id": "this is id",
"title": "this is title"}
]
2. jsonl (jsonlines) 파일 읽고 쓰기
1) 읽기
대상 jsonl => jsonl은 json이 여러 줄 있는 것
{"id": "this is id", publish_date": "this is publish_date", "title": "this is title"}
{"id": "this is id2", publish_date": "this is publish_date2", "title": "this is title2"}
{"id": "this is id3", publish_date": "this is publish_date3", "title": "this is title3"}
{"id": "this is id4", publish_date": "this is publish_date4", "title": "this is title4"}
읽기
import jsonlines
with jsonlines.open("target.jsonl") as f:
for line in f.iter():
print(line["id"]) # 각 json에 해당하는 "id" 출력
print(line["title"]) # 각 json에 해당하는 "title" 출력
2) 쓰기
import json
from collections import OrderedDict
my_data = OrderedDict()
my_data["id"] = "this is id"
my_data["title"] = "this is title"
with open("target_data.jsonl", "w", encoding="utf-8") as f:
json.dump(my_data, f, ensure_ascii=False) # ensure_ascii로 한글이 깨지지 않게 저장
f.write("\n") # json을 쓰는 것과 같지만, 여러 줄을 써주는 것이므로 "\n"을 붙여준다.
쓰기 결과 jsonl
{"id": "this is id", "title": "this is title"}
'개발용 정리' 카테고리의 다른 글
[python] decorator 정리 (3) | 2025.08.13 |
---|---|
[DBMS] 데이터 join 이해하기 (7) | 2025.08.06 |
[JavaScript] 호이스팅 (2) | 2025.07.28 |
[JavaScript] 변수 선언 var, let, const 정리 (4) | 2025.07.24 |
[CSS] 선택자 (0) | 2025.07.23 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 파이토치
- PyTorch
- #BOJ #알고리즘 #1034번
- #BOJ
- two-pointers
- #브루트포스
- javascript
- 조건부확률
- #BOJ #그리디알고리즘
- emnlp
- LeetCode
- CoT
- 인과관계추론
- DECI
- emnlp2024
- #BOJ #유클리드호제법
- directives
- iclr
- NAACL21
- python
- #information_retrieval
- 베르누이분포
- #BOJ #2467번 #투포인터알고리즘
- LLM
- Rag
- sliding window
- KL_Divergence
- llm agent
- #1405번
- GCN
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함