2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【jq コマンド】特定の要素に JSON 要素を差し込みたい【要素の追加・挿入】

Posted at

以下の original.json の ".base.data." の下に、additional.json を追加したい。

original.json
{
  "description": "sample list",
  "base": {
    "data": [
      {
        "name": "foo",
        "age": 15
      }
      // <--- ここに additional.json を追加したい
    ]
  }
}
additional.json
{
  "name": "bar",
  "age": 30
}

「jq 要素に追加する -jQuery」でググっても、「jq add 特定の要素にオブジェクトを追加する -jQuery」とググっても、-s add を使って単純にマージさせるだけの記事しか見つからなかったので、自分のググラビリティとして。

TL; DR (今北産業)

  1. 一旦、追加したい要素を変数に入れてから + 指示子で追加する。
  2. 基本構文
    jq --argjson <変数名> "<挿入したいデータ>" '<挿入したい先の要素のパス> += [$<変数名>]' <挿入したい先の JSON ファイル>
    
  3. マスター、動くものをくれ。
$ jq --argjson myentry "$(cat ./additional.json)" '.base.data += [$myentry]' ./original.json
{
  "description": "sample list",
  "base": {
    "data": [
      {
        "name": "foo",
        "age": 15
      },
      {
        "name": "bar",
        "age": 30
      }
    ]
  }
}

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?