ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【Python】json.dumps()で Unicode で表示される文字列を読めるようにする方法

python の json ライブラリを使っていて、json.dumps() で日本語が "\uXXXXXXXXXXXX" となるときの対処法をここにメモします。

デフォルトでは、json.dump や json.dumps を使用すると、Unicode文字列はエンコードされてしまいますが、「enseure_ascii = false」の指定の有無で、Unicode エスケープあり・なしの日本語が出力されます。

ensure_ascii

ensure_ascii=True or 指定なし

$ python
Python 3.11.3 (main, Apr 17 2023, 18:50:53) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> _dict = {"キー": "値"}
>>> json.dumps(_dict, indent=2 )
'{\n  "\\u30ad\\u30fc": "\\u5024"\n}'

ensure_ascii=False

$ python
Python 3.11.3 (main, Apr 17 2023, 18:50:53) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> _dict = {"キー": "値"}
>>> json.dumps(_dict, indent=2, ensure_ascii=False)
'{\n  "キー": "値"\n}'