Reputation: 313
I am trying to parse JSON that is submitted from a POST
request into a struct in a web service to send email. The following JSON is submitted in the body of the request.
{
"body": {
"template": "abctemplate.html",
"params": {
"name": "Chase",
"email": "[email protected]"
}
},
"to": [
"[email protected]",
"[email protected]"
],
"cc": [
"[email protected]",
"[email protected]"
],
"replyTo": {
"email": "[email protected]",
"name": "Jack"
},
"bcc": "[email protected]",
"subject": "Hello, world!"
}
This is mapped and read into the following struct
type emailData struct {
Body struct {
Template string `json:"template"`
Params map[string]string `json:"params"`
} `json:"body"`
To map[string]string `json:"To"` // TODO This is wrong
CC string `json:"cc"` // TODO this is wrong
ReplyTo struct {
Email string `json:"email"`
Name string `json:"name"`
}
BCC string `json:"bcc"`
Subject string `json:"subject"`
}
Both the 'to' and 'cc' JSON fields are string arrays of unknown length and do not have keys. Is there a way to map the string arrays into the struct fields? I've tried the two different ways where there are // TODO
tags with no luck. Thanks!
Upvotes: 1
Views: 4231
Reputation: 498
Use the below to convert the json to struct in golang:
Take care of the maps, which might be go struct and vice-versa.
Upvotes: 1
Reputation: 38203
Both cc
and to
are json arrays which you can unmarshal into Go slices without worrying about the length.
type emailData struct {
Body struct {
Template string `json:"template"`
Params map[string]string `json:"params"`
} `json:"body"`
To []string `json:"to"`
CC []string `json:"cc"`
ReplyTo struct {
Email string `json:"email"`
Name string `json:"name"`
}
BCC string `json:"bcc"`
Subject string `json:"subject"`
}
https://play.golang.org/p/Pi_5aSs922
Upvotes: 1