我必须将json格式的请求参数发送到API。该json请求参数为嵌套格式,因此我尝试创建请求参数的映射,然后将其转换为json格式并将其传递给api。
这是预期的json格式
{
"campaign_id": "test_notify",
"content": {
"template_id": "xxxxxxxx"
},
"recipients": [
{
"address": {"email":"xxxx@xxxxx.com"},
"substitution_data": {
"address1": "xxxx@xxxxx.com",
"address1": "xxxx@xxxxx.com"
}
}
]
}
我能够转换内容,但面临问题,以便将收件人包含在[]
中parameter := make(map[string]interface{})
parameter["campaign_id"] = "test_notify"
parameter["content"] = map[string]string{"template_id": "xxxxxxxx"}
data := make(map[string]interface{})
data["address"] = "xxxx@xxxxx.com"
data["substitution_data"] = map[string]string{
"address1":"xxxx@xxxxx.com",
"address2": "xxxx@xxxxx.com"
}
parameter["recipients"] = data
fmt.Println(data)
fmt.Println(parameter)
mapC, _ := json.Marshal(parameter)
fmt.Println(string(mapC))
我正在得到输出
{"campaign_id":"test_notify","content":{"template_id":"xxxxxxxx"},"recipients":{"address":"xxxx@xxxxx.com","substitution_data":{"address1":"xxxx@xxxxx.com","address2":"xxxx@xxxxx.com"}}}
我只需要将收件人数据括在[]中,并且我期望的请求参数将匹配。
答案 0 :(得分:2)
要将收件人包含在JSON数组中,请创建Go切片,然后附加您在data
中存储的内容。然后将切片分配给parameter["recipients"]
而不是data
。
您可以将代码更改为以下内容:
recipients := make([]map[string]interface{}, 0)
recipients = append(recipients, data)
parameter["recipients"] = recipients