1

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use the below to convert the json to struct in golang:

Json-goStruct

Take care of the maps, which might be go struct and vice-versa.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.