user857359
user857359

Reputation: 65

Nested JSON Array generation in GO

I am trying to generate a JSON payload based on a defined structure. I have found various examples of single array objects, but cannot find one that fits a multi array.

Example code (that doesn't work):

package main

import "encoding/json"
import "fmt"

type DiscMessage struct {
    Embeds []struct {
        Title       string `json:"title"`
        Description string `json:"description"`
        URL         string `json:"url"`
        Color       int    `json:"color"`
    } `json:"embeds"`
}


func main() {

var values = DiscMessage{Embeds{{"title1", "description1", "url1", 6545520}}}
encjson, _:= json.Marshal(values)
fmt.Println(string(encjson))
}

Intended output:

{
 "embeds": [{
    "title": "title1",
    "description": "description1",
    "url": "url1",
    "color": 6545520
  }]
}

What is the best approach to this? Eventually I will replace the values with variables, and the possibility of more containers, for example a full discord webhook (https://leovoel.github.io/embed-visualizer/)

Upvotes: 0

Views: 246

Answers (1)

mkopriva
mkopriva

Reputation: 38233

How to initialize a slice of anonymous struct:

type DiscMessage struct {
    Embeds []struct {
        Title       string `json:"title"`
        Description string `json:"description"`
        URL         string `json:"url"`
        Color       int    `json:"color"`
    } `json:"embeds"`
}

_ = DiscMessage{Embeds: []struct{
    Title       string `json:"title"`
    Description string `json:"description"`
    URL         string `json:"url"`
    Color       int    `json:"color"`
}{
    {"title1", "description1", "url1", 6545520},
}}

As you can see this can get too verbose for any sane mind, and if you have to do the initialization in a lot of other places it's going to be a real burden.

To remedy this you can declare the slice's element type, i.e. give it a name so it's not anonymous anymore and save yourself some unnecessary typing.

type DiscMessageEmbed struct {
    Title       string `json:"title"`
    Description string `json:"description"`
    URL         string `json:"url"`
    Color       int    `json:"color"`
}

type DiscMessage struct {
    Embeds []DiscMessageEmbed `json:"embeds"`
}

_ = DiscMessage{Embeds: []DiscMessageEmbed{{"title1", "description1", "url1", 6545520}}}

Upvotes: 2

Related Questions