LoginSignup
0
0

【Python】複数のJSONファイルを一つのJSONファイルにする方法を2つ紹介(os / globモジュール)

Posted at

概要

大量のJSONファイルを一つにまとめる、ということが必要になったのでPythonで実装しました。

ここでは2つの方法(osモジュールとglobモジュール)を紹介します。

サンプルコード2種

以下の2つ、どちらのコードでも、複数のJSONファイルを一つのJSONファイルにできます。

  • 1つ目の方法(osモジュール利用)
  • 2つ目の方法(globモジュール利用)

1つ目の方法(osモジュール利用)

import json
import os

def combine_json_files(input_folder, output_file):
    combined_data = []

    # フォルダ内の各JSONファイルを処理
    for filename in os.listdir(input_folder):
        if filename.endswith(".json"):
            file_path = os.path.join(input_folder, filename)

            # JSONファイルを読み込み
            with open(file_path, 'r', encoding='utf-8') as file:
                data = json.load(file)
                combined_data.append(data)

    # 結合したデータを出力ファイルに書き込み
    with open(output_file, 'w', encoding='utf-8') as output_file:
        json.dump(combined_data, output_file, indent=4, ensure_ascii=False)

# 入力フォルダと出力ファイルの指定
input_folder = "./raw_json_files"
output_file = "./combined_file/combined_data.json"

# JSONファイルを結合
combine_json_files(input_folder, output_file)

input_folderディレクトリに大量のJSONを置いて、このディレクトリと同階層にあるファイルを実行します。
結合されたJSONはoutput_fileに生成されています。

こちらは主にosモジュールを利用してディレクトリ内のファイルを操作しています。
例えば、os.listdir()によって対象ディレクトリ内を指定し、その中のファイルが.jsonで終わるかどうかを確認しています。

2つ目の方法(globモジュール利用)

import json
import glob

json_dir = "./raw_json_files"
output_file = "./combined_file/combined_data.json"

data = []

# ディレクトリ内の全てのJSONファイルを読み込む
for json_file in glob.glob(f"{json_dir}/*.json"):
    with open(json_file, 'r') as f:
        data.append(json.load(f))

# 結合したデータを新しいJSONファイルに保存
with open(output_file, 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

こちらはglobモジュールを使用してパターンにマッチするファイルを探す方法です。
jsonを探す場合、glob.glob(f"{json_dir}/*.json")という方法で可能です。一つ目よりだいぶ簡潔になりますね。

globモジュールとは、指定されたパターンに一致するファイルのリストを取得するためのPythonの標準ライブラリで、glob.globはその関数です。

glob モジュールは Unix シェルで使われているルールに従い指定されたパターンに一致するすべてのパス名を見つけ出します
引用元:glob --- Unix 形式のパス名のパターン展開

例えば、raw_json_filesディレクトリ内に以下のようにあるとします。

raw_json_files
├── apple.json
├── banana.json
└── lemon.json

この時、以下のコードを実行すると結果は以下の通り。

import glob

json_dir = "./raw_json_files"

json_files = glob.glob(f"{json_dir}/*.json")
print(json_files)
# ['./raw_json_files/apple.json', './raw_json_files/banana.json', './raw_json_files/lemon.json']

for json_file in json_files:
    print(json_file)

# ./raw_json_files/apple.json
# ./raw_json_files/banana.json
# ./raw_json_files/lemon.json

上記を見てわかるように、指定されたパターンに一致するファイルパスのリストを返すことがわかります。リストなのでforループで中身を取り出すことができますね。

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