import json
dict를 json 문자열로 변환
sample_dict = {'python':89,'javascript':78}
sample_dict, type(sample_dict) # ({'python': 89, 'javascript': 78}, dict)
res = json.dumps(sample_dict)
res, type(res) # ('{"python": 89, "javascript": 78}', str)
json 문자열을 dict로 변환
load_res = json.loads(res)
load_res, type(load_res) # ({'python': 89, 'javascript': 78}, dict)
dict를 json 문자열로 파일에 저장
with open('sample_dict.json','wt') as fout:
json.dump(sample_dict, fout)
json 문자열 파일을 dict로 변환
sample_dict2 = {}
with open('sample_dict.json','rt') as fin:
sample_dict2 = json.load(fin)
sample_dict2, type(sample_dict2) # ({'python': 89, 'javascript': 78}, dict)
예제
사이트에서 json 문자열을 dict를 바꾸고 dict를 다시 json 문자열로 파일에 저장한다
##
# 아래의 경로에 접속하면 json 문자열을 얻을 수 있다
# https://api.slingacademy.com/v1/sample-data/files/employees.json
# 그 json 데이터 중에서 사원정보(employees 키)만 추출하여 python_emp.json
# 파일에 저장한다
import requests
res = requests.get('https://api.slingacademy.com/v1/sample-data/files/employees.json')
sample_dict3 = json.loads(res.text)
with open('python_emp.json','wt') as fout:
json.dump(sample_dict3['employees'],fout)
##