티스토리 뷰

개발용 정리

[python] json, jsonl 파일 읽고 쓰기

공부하는묵 2021. 10. 2. 00:44

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"}

 

댓글