使用jq for sendgrid API将新数组元素添加到现有JSON数组

时间:2017-11-01 11:32:57

标签: json bash sendgrid jq

此问题与previous问题有关。

在我的情况下,我想简单地添加单个元素。我有以下input.json。

library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")

我想追加主题和template_id,以便output.json如下所示。

{
  "content": [
  ],
  "from": {
    "email": "someemail@gmail.com",
    "name": "Some Name"
  },
  "reply_to": {
    "email": "someemail@gmail.com",
    "name": "Some Name"
    },
  "personalizations": [{
    "to": [{
        "email": "someemail@gmail.com"
      },
      {
        "email": "someotheremail@gmail.com"
      }]
    }]
}

如何在bash中使用jq(包括input.json和output.json的语法)来做到这一点?

1 个答案:

答案 0 :(得分:1)

简单分配:

jq '.template_id="someID" | .personalizations[0].subject="Some subject"' input.json

输出:

{
  "content": [],
  "from": {
    "email": "someemail@gmail.com",
    "name": "Some Name"
  },
  "reply_to": {
    "email": "someemail@gmail.com",
    "name": "Some Name"
  },
  "personalizations": [
    {
      "to": [
        {
          "email": "someemail@gmail.com"
        },
        {
          "email": "someotheremail@gmail.com"
        }
      ],
      "subject": "Some subject"
    }
  ],
  "template_id": "someID"
}