json 읽어오기 (json -> dict)
import json
# json 파일 읽어오기
with open('./test.json', 'r', encoding='UTF8') as json_file:
sample_json = json.load(json_file)
print(sample_json)
# 출력: {'이름': '홍길동', '나이': 25, '특기': ['농구', '도술'], '가족관계': {'아버지': '홍판서', '어머니': '춘섬'}, '결혼 여부': True}
# json 문자열 읽어오기
json_str = '''
{
"이름": "홍길동",
"나이": 25,
"특기": ["농구", "도술"],
"가족관계": {
"아버지": "홍판서",
"어머니": "춘섬"
},
"결혼 여부": true
}
'''
sample_json2 = json.loads(json_str)
print(sample_json2)
# 출력: {'이름': '홍길동', '나이': 25, '특기': ['농구', '도술'], '가족관계': {'아버지': '홍판서', '어머니': '춘섬'}, '결혼 여부': True}
- json.load(), json.loads() 를 통해 json을 dict로 불러올 수 있다.
- json.load()는 json 파일을 읽어올때 사용한다.
- json.loads()는 json 문자열을 읽어올때 사용한다.
- 파일을 불러올때 한글깨짐을 방지하려면 open()함수에 encoding='UTF8'을 추가한다.
json 쓰기 (dict -> json)
import json
json_str = '''
{
"이름": "홍길동",
"나이": 25,
"특기": ["농구", "도술"],
"가족관계": {
"아버지": "홍판서",
"어머니": "춘섬"
},
"결혼 여부": true
}
'''
sample_json2 = json.loads(json_str)
# json 파일에 쓰기
# 한글깨짐을 방지하려면 open()함수에 encoding='UTF8'을 추가하고,
# json.dump() 함수에 ensure_ascii=False를 추가한다
with open('write.json', 'w', encoding='UTF8') as f:
json_string = json.dump(sample_json2, f, indent=2, ensure_ascii=False)
# json 객체로 저장하기
# 한글깨짐을 방지하려면 json.dump() 함수에 ensure_ascii=False를 추가한다
json_string2 = json.dumps(sample_json2, ensure_ascii=False)
- json.dump(), json.dumps() 를 통해 dict 객체를 json파일로 저장하거나 문자열로 저장할 수 있다.
- json.dump()는 json 파일로 저장할 때 사용한다.
- json.dumps()는 변수에 문자열로 저장할 때 사용한다.
- 한글깨짐을 방지하려면 open()함수에 encoding='UTF8'을 추가하고, json.dump() 함수에 ensure_ascii=False를 추가한다.
- indent 옵션을 통해 json문자열을 보기좋게 바꿀 수 있다.
'Python' 카테고리의 다른 글
[Python] Generator란? (0) | 2021.10.15 |
---|---|
[Python] iterable과 iterator (0) | 2021.10.15 |
[Python] 파이썬 가상환경(venv) 설정하기 (0) | 2021.06.18 |