jq 产生 `is not defined at <top-level>` 错误

jq produces `is not defined at <top-level>` error

像这样调用 jq 时我看到 is not defined at <top-level>:

jq ".Changes[0].ResourceRecordSet.Name = word-is-here.domain.com" someFile.json

在替换的第二侧用破折号分隔的每个单词都会重复错误。完整的错误就像

jq: error: word/0 is not defined at <top-level>, line 1:
.Changes[0].ResourceRecordSet.Name = word-is-here.domain.com

我尝试过以多种不同的方式转义引号,但都没有用。 (我的意思是做“'”'”奇怪的事情,我还在学习 bash 所以我只是把东西扔在墙上直到它粘住)

编辑: 所以我试图在 bash 脚本中 运行 这个,= 符号的两边都是变量,例如 jq --arg value "$value" --arg key "$key" '$key = $value' "$path" (我在建议后尝试的)

并得到错误: 结果为“.Changes[0].ResourceRecor...

的路径表达式无效

我使用的json是这样的:

{
  "Changes": [
    {
      "Action": "do something",
      "ResourceRecordSet": {
        "Name": "some name here to replace",
         ...
      }
    }
  ]
}
jq '.Changes[0].ResourceRecordSet.Name = "word-is-here.domain.com"' file.json

引用您要分配的字符串。或者通过参数将其传递给 jq:

jq --arg foo 'words-here' '.Changes[0].ResourceRecordSet.Name = $foo' file.json

为了将路径传递给您想要的键作为参数,https://github.com/stedolan/jq/issues/1493 的建议可能有效:

jq --argjson path '["Changes",0,"ResourceRecordSet","Name"]' \
  --arg val 'word-is-here.domain.com' \
  'getpath($path) = $val' file.json

这里的问题(或者至少是明显的问题)显然是字符串:word-is-here.domain.com,因为 jq 将破折号(“-”)解释为操作(“减号”)。

不幸的是,由于您没有给我们很多线索,所以还不完全清楚具体需要更改的内容,但合理的猜测是 word-is-here.domain.com 旨在作为固定字符串。如果是这样,您必须将其显示为 JSON 字符串。所以在 bash 或 bash-like 环境中,你可以写:

jq '.Changes[0].ResourceRecordSet.Name = "word-is-here.domain.com"' someFile.json

通过 shell 变量指定 LHS 路径

如果 LHS 路径必须由 shell 变量指定,则应尽可能将其作为 JSON 数组传入,例如使用 --argjson 命令行选项;然后可以使用 setpath($path; $value) 形式的表达式来更新路径。

如果出于某种原因,允许将 LHS 指定为 jq 路径的解决方案是首选,则可以使用 shell 字符串插值,尽管与任何此类插值一样,这应该小心完成.