如何使用jq将json的部分添加到现有文件中

时间:2016-07-25 06:53:54

标签: bash jq

我正在使用jq来解析JSON文件。我有一些带有以下内容的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"
  }
]

在此,我想添加另一个部分,如:

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

如何添加此新版块?

这是我用来提取第一部分的查询:

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

2 个答案:

答案 0 :(得分:3)

您可以使用--argjson将对象作为jq变量传递,然后使用+=将对象添加到数组中:

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

如果您不想要原始对象,请使用+代替+=

答案 1 :(得分:1)

请尝试以下“jq -s add ABC.json add.json”;

user@host:/tmp$ cat add.json
[
{
    "Value": {
    "Ref": "TEAM"
     },
     "PropagateAtLaunch": true,
         "Key": "TEAM"
     }
]
user@host:/tmp$ jq -s add ABC.json add.json  > ABCLAST.json
user@host:/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"
  }
]