0
2

More than 1 year has passed since last update.

jsonファイルの読み書き Python

Last updated at Posted at 2021-09-24

jsonファイルを読む方法です。

よく使うのでメモ

まずjsonファイルを作成

test.json
{
  "a":"1",
  "b":"2",
  "c":"3",
  "d":"4",
  "e":"5"
}

次に,jsonファイルを読み書きするプログラムです。

json_read_write.py
import json

def read_json_file(file_name):
  with open(file_name, 'r') as f:
    json_load = json.load(f)
    return json_load

def write_json_file(file_name, dict_data):
  with open(file_name, 'w') as f:
    json.dump(dict_data, f, indent=2)

if __name__ == '__main__':

  f_name = "test.json"
  data = read_json_file(f_name)

  new_data = {"a":"10"}
  data.update(new_data)

  new_data = {"f":"6"}
  data.update(new_data)

  f_name = "test2.json"

  write_json_file(f_name, data)

実行するとtest2.jsonというファイルが作成され
中身は次のようになります。

test2.json
{
  "a": "10",
  "b": "2",
  "c": "3",
  "d": "4",
  "e": "5",
  "f": "6"
}

最後に,動作確認済みの環境は次の通りです。

  • Python 2.7.18
  • Python 3.8.10

追記

ちなみに外部プログラムから使用する時は次のようになります。

test.py
from json_read_write import *

if __name__ == '__main__':

  f_name = "test.json"
  data = read_json_file(f_name)

  new_data = {"a":"10"}
  data.update(new_data)

  new_data = {"f":"6"}
  data.update(new_data)

  f_name = "test2.json"

  write_json_file(f_name, data)

github

0
2
2

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
0
2