barcode

Python으로 JSON파일 읽기

Coding/Python

JSON은 JavaScript Object Notation을 줄인 것으로, 보통 제이슨으로 읽는다. 일반적으로 클라이언트가 서버에서 가져오는 데이터는 이 형식이고, 현재 표준 형식으로 많이 쓰이고 있다. 원류는 자바스크립트지만 현재는 언어 독립적인 개별 포맷. 그러니까 누가 제이슨 파일 주세요 하면 JSON파일 달라는거지 제이슨씨 파일 주세요가 아니다 남의 파일을 왜 달라고 해

키-값 쌍으로 이루어진 데이터를 텍스트 형태로 기록해둔 것이라 휴먼 가독성은 좋다.


오늘의 도우미

{
	"Water": {
		"molecular weight": "18.016",
		"molecular formula": "H2O"
	},
	"Ethanol": {
		"molecular weight": "46.07",
		"molecular formula": "C2H5OH"
	},
	"Glucose": {
		"molecular weight": "180.156",
		"molecular formula": "C6H12O6"
	},
	"Sucrose": {
		"molecular weight": "342.3",
		"molecular formula": "C12H22O11"
	}
}

짜잔 이래뵈도 수제다 

그리고 이거 하려면 모듈 불러야 한다. 별도로 설치는 안해도 되고 

import json

이거 한줄만 추가합시다. 

 

JSON파일 읽기

with open('/home/koreanraichu/test.json') as f:
    json_data = json.load(f)
print(json.dumps(json_data))

그냥 이렇게 쓰면 알아서 불러온다. 

 

{"Water": {"molecular weight": "18.016", "molecular formula": "H2O"}, "Ethanol": {"molecular weight": "46.07", "molecular formula": "C2H5OH"}, "Glucose": {"molecular weight": "180.156", "molecular formula": "C6H12O6"}, "Sucrose": {"molecular weight": "342.3", "molecular formula": "C12H22O11"}}

형식에서 그렇게 큰 기대는 하지 말자. (참고로 VScode가 가끔 키보드 먹통이 되는 문제가 있어서 spyder로 함...)

그럼 저기서 특정 데이터만 볼 수 있어요? 예, 됩니다. 

{"Water": {"molecular weight": "18.016", "molecular formula": "H2O"}

형식이 잘 보면 딕셔너리다. 파이썬은 JSON파일을 불러올 때 딕셔너리로 불러오는데, 이 파일의 경우 다중 딕셔너리(2중)이다. 그리고 딕셔너리는 뭐다? 키-밸류로 되어 있고 키값으로 픽이 된다 그죠? 

 

print(json_data['Water'])
print(json_data['Water']['molecular formula'])

걍 이렇게 부르면 된다. 정렬도 가능하다. 

 

JSON파일 수정하기

{"Water": {"molecular weight": "18.016", "molecular formula": "H2O"}, "Ethanol": {"molecular weight": "46.07", "molecular formula": "C2H5OH"}, "Glucose": {"molecular weight": "180.156", "molecular formula": "C6H12O6"}, "Sucrose": {"molecular weight": "342.3", "molecular formula": "C12H22O11"}, "Methanol": {"molecular weight": "", "molecular formula": ""}}

여기에 메탄올에 대한 정보를 새로 추가했는데, 문제가 하나 있다. 

"Methanol": {"molecular weight": "", "molecular formula": ""}

뭐야 메탄올 정보 어디갔어요? 

이거 그럼 raw file 수정해야 하나요? ㄴㄴ 파이썬에서 커버칠 수 있다. 

json_data['Methanol']['molecular weight'] = '32.04'
json_data['Methanol']['molecular formula'] = 'CH3OH'

이런 식으로 키값을 픽해서 밸류를 수정하고 

with open ('/home/koreanraichu/test.json','w', encoding='utf-8') as s:
    json.dump(json_data,s)

이렇게 하면 들여쓰기가 가출한다. 

 

with open ('/home/koreanraichu/test.json','w', encoding='utf-8') as s:
    json.dump(json_data,s,indent = '\t')

indent = \t를 주자. 

 

JSON파일 쓰기

JSON파일을 읽고 수정해봤으면 이제 쓸 시간이다. 아니 거기 에디터 꺼요... 

 

cellphone = dict()
cellphone['Samsung'] = "Galaxy Z flip"
cellphone['Apple'] = "iPhone"
tabletpc = dict()
tabletpc['Samsung'] = 'Galaxy tab'
tabletpc['Apple'] = 'iPad'

핸드폰과 태블릿PC에 대한 딕셔너리를 생성해준다. (핸드폰 영어로 cellphone임)

 

mobile_device = dict()
mobile_device['Cellphone'] = cellphone
mobile_device['Tablet PC'] = tabletpc

그리고 두 개의 딕셔너리를 밸류로 갖는 큰 딕셔너리(모바일 기기)를 하나 만든다. 

 

with open ('/home/koreanraichu/test2.json','w', encoding='utf-8') as s:
    json.dump(mobile_device,s,indent = '\t')

그리고 묶은 딕셔너리를 그대로 JSON파일로 쓰면 이렇게 된다. 참 쉽죠?