Python/기타
[Python] Dictionary to Jason / json.dump() encoding 에러 & 한글깨짐 현상
all_sound
2023. 1. 4. 11:52
dictionary가 여러개 담긴 list인 'all_db'를 json 파일 형식으로 변경하던 중 몇 가지 에러가 발생했다.
아래는 제일 먼저 내가 실했했던 코드이다.
import json
def write_to_json(dictionary_data):
with open('db.json', 'w', encoding='UTF8') as file:
json.dump(dictionary_data, file)
write_to_json(all_db)
TypeError: Object of type int64 is not JSON serializable
다음과 타입 에러가 떴고 인코딩이 잘못 됐음을 알아챘다.
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)):
return int(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
return float(obj)
elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
return {'real': obj.real, 'imag': obj.imag}
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
elif isinstance(obj, (np.bool_)):
return bool(obj)
elif isinstance(obj, (np.void)):
return None
return json.JSONEncoder.default(self, obj)
해당 인코딩 클래스를 dump() 함수 안의 인자로 넣어주니 해결이 됐다.
import json
def write_to_json(dictionary_data):
with open('db.json', 'w', encoding='UTF8') as file:
json.dump(dictionary_data, file, cls=NumpyEncoder)
write_to_json(all_db)
json 파일이 저장이 됐고 잘 불러와 졌다.
그러나 또 한가지 문제, 한글깨짐 현상이 보였다.
dump() 함수 안의 인자로 ensure_ascii=False 를 추가해 주니 해결!!!~~
import json
def write_to_json(dictionary_data):
with open('db.json', 'w', encoding='UTF8') as file:
json.dump(dictionary_data, file, cls=NumpyEncoder, ensure_ascii=False)
write_to_json(all_db)