3
1

More than 1 year has passed since last update.

Pythonで日本語が含まれるJSONをファイルに書き込む際、可読性を上げるための最低限の設定

Posted at

概要

PythonにはJSONモジュールを使うと、JSONをファイルに書き込むことが簡単にできます。json.dump()で可能です。

ただ、オプションを何も指定せずにファイルに書き込みを行うと、以下のような状態になります。

  • 1行にまとめられた状態で書き込まれる
  • 日本語のような非ASCIIコードはエスケープされる

よって、可読性を上げる最低限の設定をする方法を挙げます。

オプション無しでjson.dump()を実行した場合

import json
tags = [{"pref": "北海道", "city": "札幌市"}, {"pref": "東京都", "city": "港区"}]

with open('./test.json', 'w') as f:
    json.dump(tags, f)

実行結果

test.jsonの内容
[{"pref": "\u5317\u6d77\u9053", "city": "\u672d\u5e4c\u5e02"}, {"pref": "\u6771\u4eac\u90fd", "city": "\u6e2f\u533a"}]

オプション無しでは「1行、非ASCIIコードはエスケープされる」という結果になります。

なお、エスケープされたJSONはjson.load()で読み込めば、問題なく読み込んでくれます。ただ、問題なく読み込めたとしても、JSONファイルをcatやlessなどで直接参照した場合、人間の目には読みにくい(実質的には読めない)ものです。

参考
with open('./test.json', 'r') as f:
    print(json.load(f))

# 結果
[{'pref': '北海道', 'city': '札幌市'}, {'pref': '東京都', 'city': '港区'}]

最低限の設定で可読性を上げる

「インデントを指定、非ASCIIコードをエスケープしない」設定をすることで、可読性の良い形で出力されます。

構文

import json
tags = [{"pref": "北海道", "city": "札幌市"}, {"pref": "東京都", "city": "港区"}]

with open('./test.json', 'w') as f:
    json.dump(tags, f, indent=4, ensure_ascii=False)

実行結果

test.jsonの内容
[
    {
        "pref": "北海道",
        "city": "札幌市"
    },
    {
        "pref": "東京都",
        "city": "港区"
    }
]

json.load()による読み込みも問題ありません。

参考
with open('./test.json', 'r') as f:
    print(json.load(f))

# 結果
[
    {
        "pref": "北海道",
        "city": "札幌市"
    },
    {
        "pref": "東京都",
        "city": "港区"
    }
]

参考

3
1
1

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
3
1