6
5

More than 5 years have passed since last update.

PythonでJSONの入出力(エンコーディングもしっかりと)

Last updated at Posted at 2019-08-08

なにこれ

備忘録

データ処理関係をJSONで保存したりするケースを考える。
JSONファイルをなんらかの方法で受け渡しし、そのファイルをいじる。
Windows環境とUNIX環境をいったりきたりするとコーディングがcp932とかになって死ぬ。

なんか毎回ググってる気がするので、Windows環境とUNIX環境で動く自分なりのJSONの入出力をまとめた。

コード

入力

import json

with open(FILE_PATH, "r", encoding="utf-8") as f:
    all_data = json.load(f)

出力

import json
import codecs

with codecs.open(FILE_PATH, 'w','utf-8') as f:
    json.dump(all_data, f, ensure_ascii=False)

おわりに

出力を以下のように書いてて同じJSONいじってて環境が変わるたび毎回死んでた。

with open(FILE_PATH, "w", encoding="utf-8") as f:
    json.dump(all_data, f)

おわり

おしり

6
5
0

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
6
5