LoginSignup
21
15

More than 3 years have passed since last update.

Python で JSON ファイルを読み書きする

Last updated at Posted at 2020-04-05

サンプルコード

import json


print('********** JSONファイルを書き出す **********')

# 辞書オブジェクト(dictionary)を生成
data = dict()
data['message'] = 'Hello, world.'
data['members'] = [
  {'name': 'アリス', 'color': '#FA3E05'},
  {'name': 'ボブ',   'color': '#FFFFAA'}
]

# 辞書オブジェクトをstr型で取得して出力
print(json.dumps(data, ensure_ascii=False, indent=2))

# 辞書オブジェクトをJSONファイルへ出力
with open('mydata.json', mode='wt', encoding='utf-8') as file:
  json.dump(data, file, ensure_ascii=False, indent=2)


print('********** JSONファイルを読み込む **********')

# JSONファイルからテキストストリームを生成
with open('mydata.json', mode='rt', encoding='utf-8') as file:
  print('file: ' + str(file))

  # 辞書オブジェクト(dictionary)を取得
  data = json.load(file)
  print('data: ' + str(type(data)))

  # JSONデータから必要な箇所を出力
  print('message: ' + data['message'])
  for member in data['members']:
    print(member['name'] + ': ' + member['color'])

実行結果

Python 3.8.2 で実行した結果。

********** JSONファイルを書き出す **********
{
  "message": "Hello, world.",
  "members": [
    {
      "name": "アリス",
      "color": "#FA3E05"
    },
    {
      "name": "ボブ",
      "color": "#FFFFAA"
    }
  ]
}
********** JSONファイルを読み込む **********
file: <_io.TextIOWrapper name='mydata.json' mode='rt' encoding='utf-8'>
data: <class 'dict'>
message: Hello, world.
アリス: #FA3E05
ボブ: #FFFFAA

出力したJSONファイル

{
  "message": "Hello, world.",
  "members": [
    {
      "name": "アリス",
      "color": "#FA3E05"
    },
    {
      "name": "ボブ",
      "color": "#FFFFAA"
    }
  ]
}

参考資料

json --- JSON エンコーダおよびデコーダ — Python 3.8.2 ドキュメント

json の API は標準ライブラリの marshal や pickle のユーザに馴染み深いものです。

組み込み型 — Python 3.8.2 ドキュメント

辞書は key: value 対のカンマ区切りのリストを波括弧でくくることで作成できます。例えば: {'jack': 4098, 'sjoerd': 4127} あるいは {4098: 'jack', 4127: 'sjoerd'} 。あるいは、 dict コンストラクタでも作成できます。

21
15
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
21
15