LoginSignup
40
20

More than 3 years have passed since last update.

PythonでJSON出力する際、日本語が文字化けする件

Last updated at Posted at 2019-05-20
●動作環境
  • Winodws 10(Pro 64bit)
  • Python 3.6.7
●事象

Pythonにて、json.dump()でJSONファイルを出力すると日本語が化ける

●原因

書込みの際、文字エンコーディングをUTF-8に指定していないため

●対応

Python標準のcodecsモジュールで書込み時のエンコーディングを
UTF-8に指定することで解決
(2021/02/19 コードサンプルを修正)

import codecs
import json

# ファイル書き込み先用オブジェクトを生成
# なお、これよりもwith句を用いたほうが、クローズ忘れを防げます
JSONFile = '/hoge/hoge.json'
fw = codecs.open(JSONFile , 'w', 'utf-8')

# JSON書き出し
dict = {"ほげ":"ほげ"}
json.dump(dict, fw, ensure_ascii=False)

# 書き込みオブジェクトを閉じる
fw.close()

# /hoge/hoge.jsonに書き出されていることを確認
40
20
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
20