0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonを使って指定したフォルダ内のJSONファイルを整形する

Posted at

はじめに

最近、JSONファイルの内容を確認する作業がありましたが、ファイルの内容が1行で記述されていました。
ファイルが少なかったらVSCodeの拡張機能などでファイルを整形しても良いと思いますが、今回はファイルが多かったので、Pythonを使ってフォルダ内のJSONファイルを整形しました。

コードの例

import argparse
import json
import os


def main():
    parser = argparse.ArgumentParser(description="対象フォルダ内のJSONファイルを整形する")

    parser.add_argument("input", help="入力フォルダパス")
    parser.add_argument("-o", "--output", help="出力フォルダパス", default="./output")

    args = parser.parse_args()

    formatting_json(args.input, args.output)


def formatting_json(in_dir, out_dir):
    # 出力フォルダがない場合、自動生成
    os.makedirs(out_dir, exist_ok=True)

    # 入力フォルダ内のJSONファイルのみのファイル名一覧を取得
    file_name_list = [f for f in os.listdir(in_dir) if f.endswith(".json")]

    # 各JSONファイルを読み込んで、整形して出力する
    for file_name in file_name_list:
        # 入力ファイル
        src_file = open(
            os.path.join(in_dir, file_name),
            "r",
            encoding="utf-8",
        )

        # 出力ファイル
        dest_file = open(
            os.path.join(out_dir, file_name),
            "w",
            encoding="utf-8",
        )

        # JSONデータを読み込む
        json_data = json.load(src_file)

        # JSONデータを整形して出力
        dest_file.write(json.dumps(json_data, indent=2, ensure_ascii=False))

        src_file.close()
        dest_file.close()


if __name__ == "__main__":
    main()

実行例と結果

・実行例

python formatting_json.py input_folder -o output_folder

・入力されたJSONファイル

input_folder/test1.json
{"list":[{"str":"test1","int":111,"bool":true},{"str":"test2","int":222,"bool":false}]}

・出力されたJSONファイル

output_folder/test1.json
{
  "list": [
    {
      "str": "test1",
      "int": 111,
      "bool": true
    },
    {
      "str": "test2",
      "int": 222,
      "bool": false
    }
  ]
}

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?