본문 바로가기
Dev/파이썬

파이썬에서 json 파일 읽고 쓰기

by bsion 2018. 8. 15.

Json?


json 이란 여러 프로그래밍언어에서 사용할 수 있는 데이터타입이다. 파이썬 dictionary 와 유사한 구조를 갖고있다. 비슷한 다른 데이터타입 중에는 yaml 등이 있다.

파이썬을 설치하면 (아마) 기본적으로 json 라이브러리는 설치가 되어있다.

import json

import 에러가 발생하면 간단히 pip install json 으로 설치하면 끝



.json 파일 읽기


json 파일은 기본적으로 파이썬의 dictionary 타입으로 로드를 한다. 기본 로직은 파일을 string 타입으로 읽은 후 dictionary 형태로 변형시키는 것이다.

import json

jstring = open("filename.json", "r").read()
dict = json.loads(jstring)

그러나 이와같이 dictionary 형태로 로드 할경우에, 파이썬의 dictionary 의 특성상 key 가 원래순서대로 유지가 되지 않는다. 

따라서 필요에 따라 순서가 있는 dictionary 로 로드할수도 있다.

import json
from collections import OrderedDict

jstring = open("filename.json", "r").read()
dict = json.loads(jstring, object_pairs_hook=OrderedDict)



.json 파일로 저장하기


마찬가지로 json 타입 파일로 저장하기 위해서는 파이썬 dictionary 가 필요하고 이를 json 타입으로 저장시킨다. 마찬가지로 dictionary 를 우선 string 타입으로 변환후 파일쓰기를 하면된다.

import json

jstring = json.dumps(dict, indent=4)
f = open(filename, "w")
f.write(jstring)
f.close()

위 코드에 보면 indent 항목이 있는데 json 파일의 들여쓰기를 뜻한다. 




댓글