I want to create JSON like this:
{
"name": "val1",
"version": "val2",
"type": "val3",
"settings": [
"setting1,
"setting2",
"setting3",
[
"option1",
"option2"
]
]
}
But I don't know how to create the nested array inside settings:
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Name string `json:"name"`
Version string `json:"version"`
Type string `json:"type"`
Settings []string `json:"settings"`
}
func main() {
settings := []string{"setting1", "setting2", "setting3"}
options := []string{"option1", "option2"}
setopts := append(settings, options...)
c := &Config{"val1", "val2", "val3", setopts}
j, err := json.Marshal(c)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}
Output piped through jq for readability:
$ ./main | jq
{
"name": "val1",
"version": "val2",
"type": "val3",
"settings": [
"setting1",
"setting2",
"setting3",
"option1",
"option2"
]
}
The result is that option1 and option2 is values inside settings array, but they should be inside a nested array of settings instead. Also, the options may not always be present when marshaling and in those cases the nested array should not be created.
How can I accomplish this?