简体   繁体   中英

How to create multilevel map in golang

I have to send request parameter in json format to an API. This json request parameter is in nested format, so I am trying to create a map of request parameters and then convert it in json format and pass it to api.

This is expected json format

{
  "campaign_id": "test_notify",
  "content": {
    "template_id": "xxxxxxxx"
  },
  "recipients": [
    {
      "address": {"email":"xxxx@xxxxx.com"},
      "substitution_data": {
        "address1": "xxxx@xxxxx.com",
        "address1": "xxxx@xxxxx.com"
      }
    }
  ]
  }

I am able to convert till content but facing issue to enclose recipients in []

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))

I am getting output

{"campaign_id":"test_notify","content":{"template_id":"xxxxxxxx"},"recipients":{"address":"xxxx@xxxxx.com","substitution_data":{"address1":"xxxx@xxxxx.com","address2":"xxxx@xxxxx.com"}}}

I just need to enclose recipients data in [] and my expected requesting parameter will match.

To enclose the recipients in a JSON array, create a Go slice and append what you have stored in data . Then assign the slice to parameter["recipients"] instead of data .

You could change your code to something like this:

recipients := make([]map[string]interface{}, 0)
recipients = append(recipients, data)
parameter["recipients"] = recipients

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM