Issue passing array of JSON to variables
bradpurchase opened this issue · 2 comments
I am having a hard time figuring out how to make this library send a variable whose value is an array of JSON.
My code looks essentially like this:
package main
import (
"fmt"
"log"
"os"
mailjet "github.com/mailjet/mailjet-apiv3-go"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main () {
mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
items := []Item{
{
ID: 1,
Name: "Hello",
},
{
ID: 2,
Name: "World",
},
}
itemsJSON, err := json.Marshal(items)
if err != nil {
log.Fatal(err)
}
messagesInfo := []mailjet.InfoMessagesV31{
mailjet.InfoMessagesV31{
From: &mailjet.RecipientV31{
Email: "brad@test.com",
Name: "Brad",
},
To: &mailjet.RecipientsV31{
mailjet.RecipientV31 {
Email: "passenger1@example.com",
Name: "passenger 1",
},
},
TemplateID: 1234567,
TemplateLanguage: true,
Subject: "This is my test email",
Variables: map[string]interface{}{
"query_string": "foo",
"items": string(itemsJSON),
},
},
}
messages := mailjet.MessagesV31{Info: messagesInfo}
res, err := m.SendMailV31(&messages)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Data: %+v", res)
}
In my template, I want to use mjml code like {% for item in var:items %}
and display some HTML within each iteration to present to the user. Pretty simple use case from what I understand, and I can get that part working if I try sending a cURL version of this - it has no problem with the array variable.
With the above Go code I get a template language error upon sending complaining about the items
variable not being an array, e.g.:
A template language occurred when sending a message using Template 1234567: "var:items" is not an array value
This error makes sense in a way, because I am sending it as a string as otherwise itemsJSON
will be a slice of bytes, which is certainly incorrect. However I am unsure how to get Mailjet to read what I'm passing as an array and have things work as expected in this case. Please help!
Hey Brad.
Have you tried sending it without marshaling an array manually first, like
Variables: map[string]interface{}{
"query_string": "foo",
"items": items,
},
It could be that you're marshaling it twice in this example, once manually and then implicitly inside SendMailV31
Hello, I'm having the same issue trying to use an array as variable for MailJet, keeping the same code example above I tried both:
Variables: map[string]interface{}{
"query_string": "foo",
"items": items,
},
and
Variables: map[string]interface{}{
"query_string": "foo",
"items": string(itemJSON),
},
In the first case the email was sent but the array is empty, in the second case the email was blocked by MailJet (so I think there is a syntax issue, the same as above).
The code on MailJet is very simple and from the Test section it works:
{% for item in var:items %}
Item: {{item.name}}
{% endfor %}
Any suggestion?
Thanks
Paolo