以下のような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データの加工, 整形)の使い方