8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでJSONファイルを作成する方法

Last updated at Posted at 2020-06-07

はじめに

Pythonのjsonモジュールでは、JSONファイルを読み込んだり、JSON形式のオブジェクトを書き込むことはできるが、JSONファイルを作成することはできない。JSONファイル作成を、必要に迫られ実装したので、メモとして残しておく。

公式ドキュメントより
https://docs.python.org/ja/3/library/json.html
image.png

実装方針

  • 書き込みたいJSONファイルが空なら [ を挿入する
  • JSON形式のオブジェクトを挿入する
  • 末尾に ] を挿入する
  • 次に挿入するとき、末尾が ] なら , に置き換える

実装例

以下の3ファイルは同階層にあるものとする

json_make.py
import json
from pathlib import Path

def json_make(path: Path, obj: dict) -> None:
    ls = None
    with open(path, 'r+') as f:
        ls = f.readlines()
        if ls == []:
            ls.append('[\n')
        if ls[-1] == ']':
            ls[-1] = ','
        ls.insert(len(ls), f'{json.dumps(obj, indent=4 ,ensure_ascii=False)}')
        ls.insert(len(ls), '\n]')

    with open(path, 'w') as f:
        f.writelines(ls)
main.py
from json_make import json_make
from pathlib import Path

def main():
    path = Path(__file__).parent/'tmp.json'
    dict_obj = {'key1':'value1', 'key2':'value2', 'key3':['value3', 'value4']}
    json_make(path, dict_obj)


if __name__ == '__main__':
    main()

json.dumps(indent = 0) の場合

tmp.json
[
{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
]

json.dumps(indent = 4) の場合

tmp.json
[
{
    "key1": "value1",
    "key2": "value2",
    "key3": [
        "value3",
        "value4"
    ]
}
,{
    "key1": "value1",
    "key2": "value2",
    "key3": [
        "value3",
        "value4"
    ]
}
,{
    "key1": "value1",
    "key2": "value2",
    "key3": [
        "value3",
        "value4"
    ]
}
,{
    "key1": "value1",
    "key2": "value2",
    "key3": [
        "value3",
        "value4"
    ]
}
]

参照

公式ドキュメント

終わりに

もっと良い書き方があれば教えてください

8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?