[python]파이썬: json 읽기, 쓰기


json 읽기, 쓰기 예제

예제를 진행하기 앞서 json 파일로 만들 file_data입니다.

import json

file_data = dict()
file_data["name"] = "example"
file_data["date"] = "2019-04-10"
file_data["num"] = 20190410
file_data["kr"] = "한글예제"

# 출력
# {'name': 'example', 'date': '2019-04-10', 'num': 20190410, 'kr': '한글예제'}



json 형태의 데이터 만들기

# python dictionary converted into json
json.dumps(file_data, ensure_ascii=False, indent="\t")

# 출력
# {
#      'name': 'example',
#      'date': '2019-04-10',
#      'num': 20190410,
#      'kr': '한글예제'
# }

json,dumps()

Notes

python type의 데이터 객체를 JSON 타입으로 변환한다.

json 모듈은 비라틴 문자열에 대해서 ascii 인코딩을 적용하여 유니코드 코드 포인트 표현으로 변환합니다.
json 파일 내에 읽을 수 있는 형태로 문자열을 그대로 저장하고 싶다면 ensure_ascii=False를 주어야 합니다.

indent='\t'를 주지 않으면 json 모듈이 값을 일렬로 출력시킵니다.


ensure_ascii=False를 주지 않았을 경우

json.dumps(file_data, indent="\t")

# 출력
# {
#      'name': 'example',
#      'date': '2019-04-10',
#      'num': 20190410,
#      'kr':'\ud55c\uae00\uc608\uc81c'
# }


indent="\t"를 주지 않았을 경우

json.dumps(file_data, ensure_ascii=False)



json 파일 생성(쓰기)

# create json file
with open("example.json", "w", encoding="utf-8") as fp:
    json.dump(file_data, fp, ensure_ascii=False, indent="\t")

# example.json
# {
#    "name": "example", 
#    "date": "2019-04-10", 
#    "num": 20190410, 
#    "kr": "한글예제"
# }

json.dump()

Notes

json 형태 데이터를 만들땐느 json.dumps를 사용하지만 파일을 저장할 경우에는 json.dump를 사용합니다.
ensure_ascii=False, indent="\t" 의미는 "json 형태의 데이터 만들기" 와 동일합니다.


ensure_ascii=False, indent="\t"를 주지 않았을 경우

with open("example.json", "w", encoding="utf-8") as fp:
    json.dump(file_data, fp)

# example.json
# {"name": "example", "date": "2019-04-10", "num": 20190410, "kr": "\ud55c\uae00\uc608\uc81c"}



json 파일 읽기

# read json file as python
with open("example.json", "r", encoding="utf-8") as fp:
    json.load(fp)

# 출력
# {'name': 'example', 'date': '2019-04-10', 'num': 20190410, 'kr': '한글예제'}

json.load(fp)

Notes

json 파일을 python dictionary 형태로 읽어들입니다.
encoding="utf-8"을 사용하지 않으면 UnicodeDecodeError: 'cp949' 에러가 발생할 수 있으니 주의하셔야 합니다.


encoding="utf-8"을 사용하지 않았을 경우

with open("example.json""r"as fp:
    json.load(fp)

Notes

encoding="utf-8"을 사용하지 않았다고 무조건 cp949 에러가 발생하지는 않습니다.



참고문헌

댓글

이 블로그의 인기 게시물

[opencv-python] 이미지 크기조절(resize) 하는 법

[python] selenium close와 quit 차이점

[python]파이썬: csv reader header skip (첫번째 행 무시하기, 안읽기)