Why it doesn't work?

作業のメモ、記録をブログに残しています。

Python JSONで日本語を出力する

Python GeoJSONファイルを出力する - Why it doesn't work?で出力するGeoJSONファイルに日本語の項目を追加しようとしている。Pythonのバージョンは2.7.14。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

property = {"Content": "右方向です。"}
print json.dumps(property)

試しに上記のようなスクリプトを実行すると、以下のような結果が出力された。Unicode...

{"Content": "\u53f3\u65b9\u5411\u3067\u3059\u3002"}

仕様を参照すると、以下のような記載がある。

If ensure_ascii is true (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result is a str instance consisting of ASCII characters only.

要は、デフォルトではアスキー以外の文字は、Unicodeのコードそのものが出力されると言うことらしい。
と言うことで、"ensure_ascii"を"False"に設定してみる。

print json.dumps(property, ensure_ascii=False)

{"Content": "右方向です。"}

うまく行ったようだ。
なお、エンコードのデフォルトは以下の通り、"UTF-8"ということなので今回は指定していないが、念のため仕様から転載しておく。

encoding is the character encoding for str instances, default is UTF-8.