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

假设您的新数组元素位于 shell 数组中,如下所示:

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,这些字符串可用作 array $ARGS.positional,我们只需将此数组分配到文档中的正确位置即可。

如果您将新值作为标量 shell 变量中的有效 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

请注意,您必须--argjson在此处使用,因为您想要jq用作$aJSON 文档片段,而不是将值编码为字符串。

相关内容