使用重定向运算符通过jq更新文件的内容

时间:2017-07-12 15:12:57

标签: json cygwin jq

我的JSON输入文件如下:

{
"Name":"SA",
"Password":"yyyyy",
"Mappings" : {
"RegionMap" : {
   "us-east-1"      : { "AMI" : "xxxxxx" },
   "us-east-2"      : { "AMI" : "" },
   "us-west-1"      : { "AMI" : "" },
   "us-west-2"      : { "AMI" : "" },
   "ca-central-1"   : { "AMI" : "" },
   "eu-central-1"   : { "AMI" : "" },
   "eu-west-1"      : { "AMI" : "" },
   "eu-west-2"      : { "AMI" : "" },
   "ap-south-1"     : { "AMI" : "" },
   "ap-southeast-1" : { "AMI" : "" },
   "ap-southeast-2" : { "AMI" : "" },
   "ap-northeast-1" : { "AMI" : "" },
   "ap-northeast-2" : { "AMI" : "" },
   "sa-east-1"      : { "AMI" : "" }       
   }
 }
}

我的任务是更新给定json文件中AMI的{​​{1}}键的值,并将更新的文件创建为新文件。我正在使用带有重定向运算符的jq插件。它有+运算符,可用于对象中的us-east-1内容。

我的overwrite输出

expected

我当前的命令未提供预期的输出,其内容如下:

{
"Name":"SA",
"Password":"yyyyy",
"Mappings" : {
"RegionMap" : {
   "us-east-1"      : { "AMI" : "abcd" },
   "us-east-2"      : { "AMI" : "" },
   "us-west-1"      : { "AMI" : "" },
   "us-west-2"      : { "AMI" : "" },
   "ca-central-1"   : { "AMI" : "" },
   "eu-central-1"   : { "AMI" : "" },
   "eu-west-1"      : { "AMI" : "" },
   "eu-west-2"      : { "AMI" : "" },
   "ap-south-1"     : { "AMI" : "" },
   "ap-southeast-1" : { "AMI" : "" },
   "ap-southeast-2" : { "AMI" : "" },
   "ap-northeast-1" : { "AMI" : "" },
   "ap-northeast-2" : { "AMI" : "" },
   "sa-east-1"      : { "AMI" : "" }       
   }
 }
}

有人可以帮助我使用重定向运算符实现预期的输出吗?

我在jq '.Mappings.RegionMap + { "us-east-1":{"AMI":"abcd"}}' <OldfileName> > <Newfilename> 环境中运行该命令,jq版本为cygwin

修改

在密码密钥后添加逗号

1 个答案:

答案 0 :(得分:2)

使您的输入json无效的第一个问题是此行(第3行):

...
"Password":"yyyyy"  <----
...

应该跟,

修复后,您可以轻松更新所需的属性值:

jq '.Mappings.RegionMap["us-east-1"].AMI = "abcd"' oldfile > newfile

newfile内容:

{
  "Name": "SA",
  "Password": "yyyyy",
  "Mappings": {
    "RegionMap": {
      "us-east-1": {
        "AMI": "abcd"
      },
      "us-east-2": {
        "AMI": ""
      },
      "us-west-1": {
        "AMI": ""
      },
      "us-west-2": {
        "AMI": ""
      },
      "ca-central-1": {
        "AMI": ""
      },
      "eu-central-1": {
        "AMI": ""
      },
      "eu-west-1": {
        "AMI": ""
      },
      "eu-west-2": {
        "AMI": ""
      },
      "ap-south-1": {
        "AMI": ""
      },
      "ap-southeast-1": {
        "AMI": ""
      },
      "ap-southeast-2": {
        "AMI": ""
      },
      "ap-northeast-1": {
        "AMI": ""
      },
      "ap-northeast-2": {
        "AMI": ""
      },
      "sa-east-1": {
        "AMI": ""
      }
    }
  }
}