jqはjsonファイル内の「[]」ブロックを検索して置き換えます。

jqはjsonファイル内の「[]」ブロックを検索して置き換えます。

run_list間の値を削除し、[]で定義した変数に置き換える必要がありますa

実行リスト:

{
  "name": "blah200.blah.stage.blahblah.com",
  "chef_environment": "blahenv",
  "run_list": [
  "recipe[blah1]",
  "recipe[blah2]",
  "recipe[blah3]",
  "recipe[blah4]",
  "recipe[blah5]",
  "recipe[blah6]",
  "recipe[blah7]",
  "recipe[blah8]",
  "recipe[blah9]"
]
,
  "normal": {
    "tags": [
      "run_once"
    ],
    "selinux": {
      "status": "disabled"
    },
    "blah_pkger": {
      "access": {
        "blah": "x.x.x.x"
      }
    }
  }
}
a="[ recipe[blah11], recipe[blah12], recipe[blah12], recipe[blah13], recipe[blah14], recipe[blah15], recipe[blah16], recipe[blah17], recipe[blah18], recipe[blah19], recipe[blah20], recipe[blah21], recipe[blah22], recipe[blah23] ]"

私は私が次のことをすることができることを知っています。

jq --args newval $a '(.run_list[]| select(.run_list))|= $newval' file.json > tmp.json

ただし、次のエラーは発生しません。

jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at <top-level>, line 1:

ベストアンサー1

新しい配列要素が次のシェル配列にあるとします。

a=(
        'recipe[blah11]' 'recipe[blah12]' 'recipe[blah12]' 'recipe[blah13]'
        'recipe[blah14]' 'recipe[blah15]' 'recipe[blah16]' 'recipe[blah17]'
        'recipe[blah18]' 'recipe[blah19]' 'recipe[blah20]' 'recipe[blah21]'
        'recipe[blah22]' 'recipe[blah23]'
)

run_listその後、配列を次の要素に置き換えることができます。

jq '.run_list = $ARGS.positional' file --args "${a[@]}"

...文書が保存される場所ですfile

オプション--argsはコマンドラインの最後のオプションでなければならず、配列jqはその後に個別に引用された文字列に展開されます。式内では、jqこれらの文字列は配列として使用可能であり、$ARGS.positionalこの配列を文書の正しい場所に割り当てるだけです。

スカラーシェル変数に有効なJSON配列で新しい値を渡す場合

a='[
  "recipe[blah11]", "recipe[blah12]", "recipe[blah12]", "recipe[blah13]",
  "recipe[blah14]", "recipe[blah15]", "recipe[blah16]", "recipe[blah17]",
  "recipe[blah18]", "recipe[blah19]", "recipe[blah20]", "recipe[blah21]",
  "recipe[blah22]", "recipe[blah23]"
]'

それではあなたはできます。

jq --argjson value "$a" '.run_list = $value' file

値を文字列にエンコードするのではなくJSONドキュメントの断片として使用するには、--argjsonここで使用する必要があります。jq$a

おすすめ記事