2017-07-12 185 views
2

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文件更新的us-east-1AMI關鍵的價值,創造更新的文件作爲新文件。我正在使用帶重定向操作符的jq插件。它有+運算符,可以用於對象中的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> 

有人可以幫我實現與使用重定向操作符預期的輸出?

我在cygwin環境中運行命令,我的jq版本是1.5

編輯

增加了密碼鑰匙

回答

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": "" 
     } 
    } 
    } 
} 
+0

@RomanPerekrest感謝。有效。另請參閱我的編輯 – shubhamagiwal92

+0

@ shubhamagiwal92,不客氣 – RomanPerekhrest

+0

不是什麼大不了的事情,但在這種情況下,我只會使用簡單的賦值'=',因爲您正在分配固定值。如果您需要當前值來確定新值,我會保留'| =''。 –