-
[yongggg's] json, jsonl 파일 read & writeError 관련 2025. 1. 23. 09:20
안녕하세요 이번 장에서는 json 파일과 jsonl 파일을 읽고 쓰는 방법에 대해 알아보겠습니다.
1. json 파일 읽고 쓰기
1-1) read .json file
만약 json file name이 "target.json" 이라면, 다음과 같은 코드로 .json file을 읽을 수 있다.
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" 출력
1-2) write .json file
또, 다음과 같은 코드로 예제 json list인 "my_data"를 저장공간에 쓸 수 있다.
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) # indent=4, ensure_ascii=False 인자는 json file을 보기 좋게 저장하도록 한다.
2. jsonl (jsonlines) 파일 읽고 쓰기
2-1) read .jsonl file
jsonl file은 json 형식의 줄이 여러개 있는 것을 말하며, 다음과 같은 코드로 "target.jsonl file"을 읽을 수 있다.
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-2) write .jsonl file
또, 다음과 같은 코드로 "my_data"를 .jsonl 형식으로 저장 공간에 쓸 수 있다.
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"을 붙여준다.
'Error 관련' 카테고리의 다른 글