LoginSignup
2
0

More than 1 year has passed since last update.

複数あるjsonファイルを1つのjsonファイルにしたい

Last updated at Posted at 2022-02-11

以下のようなjsonが複数あり、順番に生成される状況であったとする。
この状況下で以下を行いたい

  • indexを取得する
  • index以外を抜き出す
  • jsonファイルを新しく作る
  • indexをキーにして1つのjsonファイルにする。(test1.json,test2.json...testn.json --> test.json

jsonファイル

test1.json
{
  "test": {
    "index":1
    "testtest": [
      123,
      456
    ]
  }
}
test2.json
{
  "test": {
    "index":2
    "testtest": [
      789,
      012
    ]
  }
}
  • indexを取得する
$ jq .test.index test1.json
1
  • index以外を抜き出す
$ jq 'del(.test.index)' test1.json
{
  "test": {
    "testtest": [
      123,
      456
    ]
  }
}
  • jsonファイルを新しく作る
$ echo {} | jq . > file.json
$ jq . file.json 
{}
  • indexをキーにして1つのjsonファイルにする。(test1.json,test2.json...testn.json --> test.json
do.sh
OUTPUTJSON="output.json"
echo {} | jq . > ${OUTPUTJSON}
# loop N
LOOP_MAX=2
for N in `seq 1 ${LOOP_MAX}`; do
    # get index
    INDEX=`jq .test.index test${N}.json`
    # get json without index
    TESTJSON_WITHOUT_INDEX=`jq 'del(.test.index)' test${N}.json`
    # update ${OUTPUTJSON}
    jq ".index${N} = ${TESTJSON_WITHOUT_INDEX}" ${OUTPUTJSON} > tmp && mv tmp ${OUTPUTJSON}
done
jq . ${OUTPUTJSON}
$ bash do.sh
{
  "index1": {
    "test": {
      "testtest": [
        123,
        456
      ]
    }
  },
  "index2": {
    "test": {
      "testtest": [
        789,
        12
      ]
    }
  }
}

キーの概念と微妙に異なる部分があるかもしれないが、やりたい事はできている。

参考

jq コマンドで新規JSONファイルを生成するには
jq で複数の JSON ファイルを結合して書き出す
jqコマンド(jsonデータの加工, 整形)の使い方

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