You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jq批量替换JSON文件中的值并返回完整内容

使用jq修改JSON中多个嵌套字段的值

原始JSON结构

[{"version": 0.0,"Resources": [ {"TargetService": {"Type": "AWS::ECS::Service","Properties": {"TaskDefinition": "abc","LoadBalancerInfo": {"ContainerName": "def","ContainerPort": 8080}}}} ]}]

需求

将TaskDefinition的值从"abc"改为"123",同时将ContainerName的值从"def"改为"456",返回完整的更新后JSON。

错误尝试及结果

尝试的命令:

echo $APP_SPEC | jq --arg TASK_DEFINITION "123" '(.[].Resources[].TargetService | select(.Properties)).TaskDefinition |=$TASK_DEFINITION'

错误返回结果:

[ { "version": 0, "Resources": [ { "TargetService": { "Type": "AWS::ECS::Service", "Properties": { "TaskDefinition": "abc", "LoadBalancerInfo": { "ContainerName": "container_name", "ContainerPort": 8080 } }, "TaskDefinition": "123" } } ] } ] 

问题原因:路径定位错误,没有指向Properties内部的TaskDefinition字段,而是直接在TargetService层级新增了一个同名字段,而非修改原有字段。

正确的jq命令

方法一:通过管道批量修改字段

echo "$APP_SPEC" | jq --arg newTaskDef "123" --arg newContainerName "456" '
.[].Resources[].TargetService.Properties |= (
    .TaskDefinition = $newTaskDef |
    .LoadBalancerInfo.ContainerName = $newContainerName
)
'

方法二:直接定位路径赋值

echo "$APP_SPEC" | jq --arg td "123" --arg cn "456" '
.[].Resources[].TargetService.Properties.TaskDefinition = $td |
.[].Resources[].TargetService.Properties.LoadBalancerInfo.ContainerName = $cn
'

正确输出结果

[
  {
    "version": 0.0,
    "Resources": [
      {
        "TargetService": {
          "Type": "AWS::ECS::Service",
          "Properties": {
            "TaskDefinition": "123",
            "LoadBalancerInfo": {
              "ContainerName": "456",
              "ContainerPort": 8080
            }
          }
        }
      }
    ]
  }
]

内容的提问来源于stack exchange,提问作者Abhi.G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:45:42