2016-07-25 20 views
0

我正在使用jq來解析JSON文件。我有以下內容如何使用jq將json的部分添加到現有文件中

[ 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TNAM" 
    }, 
    "Key": "Name" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TAPP" 
    }, 
    "Key": "application" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TENV" 
    }, 
    "Key": "environment" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TSHA" 
    }, 
    "Key": "shared" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TTER" 
    }, 
    "Key": "tier" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "CostCenter" 
    }, 
    "Key": "cost-center" 
    } 
] 

JSON文件的某些部分在此我想補充像另一個部分:

{ 
    "Value": { 
    "Ref": "TEAM" 
    }, 
    "PropagateAtLaunch": true, 
    "Key": "TEAM" 
} 

我如何添加這個新的部分?

這是我用於提取所述第一部分中的查詢:

$ cat ABC.json | jq '.Resources.ASGRP.Properties.Tags' 

回答

3

您可以傳遞對象爲使用--argjson一個JQ變量,然後使用+=對象添加到陣列:

jq --argjson obj '{"sample": "object"}' '.Resources.ASGRP.Properties.Tags += [$obj]' 

如果你不想原來的對象,請使用+代替+=

+0

謝謝聖地亞哥。這也有助於我在另一個用例實現中。 –

1

嘗試此「jq -s add ABC.json add.json」,如下;

[email protected]:/tmp$ cat add.json 
[ 
{ 
    "Value": { 
    "Ref": "TEAM" 
    }, 
    "PropagateAtLaunch": true, 
     "Key": "TEAM" 
    } 
] 
[email protected]:/tmp$ jq -s add ABC.json add.json > ABCLAST.json 
[email protected]:/tmp$ cat ABCLAST.json 
[ 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TNAM" 
    }, 
    "Key": "Name" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TAPP" 
    }, 
    "Key": "application" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TENV" 
    }, 
    "Key": "environment" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TSHA" 
    }, 
    "Key": "shared" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TTER" 
    }, 
    "Key": "tier" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "CostCenter" 
    }, 
    "Key": "cost-center" 
    }, 
    { 
    "PropagateAtLaunch": true, 
    "Value": { 
     "Ref": "TEAM" 
    }, 
    "Key": "TEAM" 
    } 
] 
+0

謝謝你Dogru。這幫助了我很多。 –

相關問題