使用 JQ 更新 json 对象的部分值

update part of a value of a json object using JQ

在 JSON 对象中有一个值,其中包含一个需要使用 JQ 更新的变量,下面是我用来更新 accountid[=25 的子文件和 jq 命令=] 在 json 文件中

{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}

JQ命令

jq 'map(.$accountid = "123")' myjson.json

错误

jq: error (at myjson.json:1): Cannot index string with string "$accountid"

我是不是漏了什么?

从评论来看,您似乎应该使用 map_values,也许 sub 之类的东西。因此考虑这个例子:

echo '{"bucketname":"test/$accountid/123","objectname":"test/$accountid/123","targetlocation":"$TARGET_LOCATION"}' |
 jq 'map_values( sub("[$]accountid";"123") )'

产生:

{
  "bucketname": "test/123/123",
  "objectname": "test/123/123",
  "targetlocation": "$TARGET_LOCATION"
}

锐化

您可能希望提高替换标准,例如

sub("[$]accountid(?<tail>(/|$))"; "123\(.tail)" )