0
0

JSONファイルに項目を一気に追加するスクリプトメモ

Last updated at Posted at 2024-05-13

JSONファイルに項目追加したい!

header.typeIdとheader.hogeという項目があるすべてのJSONファイルに、
header.dataA,header.dataB.header.dataCという項目を入れます。三つの項目の値は固定値

ただし、対象のJSONファイルは1000個!

やってられるかよ。

ということでシェルを組んでみた。

#!/bin/bash

# スクリプトが存在するディレクトリを取得
TARGET_DIR="$(dirname "$(realpath "$0")")"

# 固定値の定義
dataA="1234567890abcdef1234567890abcdef"  # UUIDからハイフンを除いた値
dataB="20240101000000"                     # 日付と時刻の固定値
dataC="AAAAA"                               # 固定文字列

# 対象ディレクトリ内およびサブディレクトリ内のすべてのJSONファイルに対して処理を行う
find "$TARGET_DIR" -type f -name '*.json' | while read -r file; do
    # jqコマンドを使ってJSONを更新
    jq --indent 4 '
      if .header | has("typeId") and has("hoge") then
        .header |= {
          dataA: $dataA,
          dataB: $dataB,
          typeId: .typeId,
          hoge: .hoge,
          dataC: $dataC
        }
      else
        .
      end
    ' --arg dataA "$dataA" --arg dataB "$dataB" --arg dataC "$dataC" "$file" > "$file.tmp"
    
    # ファイルが変更されたかを確認し、変更されていれば更新
    if ! cmp -s "$file" "$file.tmp"; then
        mv "$file.tmp" "$file"
        echo "Updated: $file"
    else
        rm "$file.tmp"
    fi
done

echo "JSONファイルの更新が完了しました。"


こういうの何も見ずにささっと書きたいですね。

追記、JSONが使えないので、Javaでやることにしました...

ヘッダークラスを準備


import com.fasterxml.jackson.annotation.JsonProperty;

public class Header {
    @JsonProperty("dataA")
    private String dataA;

    @JsonProperty("dataB")
    private String dataB;

    @JsonProperty("typeId")
    private String typeId;

    @JsonProperty("hoge")
    private String hoge;

    @JsonProperty("dataC")
    private String dataC;

    // Getters and Setters
    public String getDataA() {
        return dataA;
    }

    public void setDataA(String dataA) {
        this.dataA = dataA;
    }

    public String getDataB() {
        return dataB;
    }

    public void setDataB(String dataB) {
        this.dataB = dataB;
    }

    public String getTypeId() {
        return typeId;
    }

    public void setTypeId(String typeId) {
        this.typeId = typeId;
    }

    public String getHoge() {
        return hoge;
    }

    public void setHoge(String hoge) {
        this.hoge = hoge;
    }

    public String getDataC() {
        return dataC;
    }

    public void setDataC(String dataC) {
        this.dataC = dataC;
    }
}

メイン処理

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

public class JsonModifier {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        File directory = new File("/path/to/your/json/files"); // JSONファイルが存在するディレクトリ
        File[] files = directory.listFiles((dir, name) -> name.endsWith(".json"));

        if (files != null) {
            for (File file : files) {
                try {
                    // JSONファイルからJavaオブジェクトへの読み込み
                    Header header = mapper.readValue(file, Header.class);

                    // 必要なデータを設定
                    header.setDataA("some_constant_UUID_without_hyphens");
                    header.setDataB("20220501123045");
                    header.setDataC("AAAAA");

                    // JavaオブジェクトからJSONファイルへの書き込み
                    mapper.writerWithDefaultPrettyPrinter().writeValue(file, header);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("All JSON files have been updated.");
    }
}

```java
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

public class JsonModifier {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        File directory = new File("/path/to/your/json/files"); // JSONファイルが存在するディレクトリ
        File[] files = directory.listFiles((dir, name) -> name.endsWith(".json"));

        if (files != null) {
            for (File file : files) {
                try {
                    // JSONファイルからJavaオブジェクトへの読み込み
                    Header header = mapper.readValue(file, Header.class);

                    // 必要なデータを設定
                    header.setDataA("some_constant_UUID_without_hyphens");
                    header.setDataB("20220501123045");
                    header.setDataC("AAAAA");

                    // JavaオブジェクトからJSONファイルへの書き込み
                    mapper.writerWithDefaultPrettyPrinter().writeValue(file, header);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("All JSON files have been updated.");
    }
}

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