首页 > 解决方案 > 使用 JQ 更新 json 对象的部分值

问题描述

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

{"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"

我在这里错过了什么吗?

标签: jsonshelljqsubstitution

解决方案


从评论看来,您应该使用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)" ) 

推荐阅读