0

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?

1 Answer 1

4

The output that you show here:

    "setting1",
    "setting2",
    "setting3",
    [
      "option1",
      "option2"
    ]

can be described as JSON string or array-of-strings.

You may model this with []interface{}, and append to it either strings or slices:

type Config struct {
        Name     string        `json:"name"`
        Version  string        `json:"version"`
        Type     string        `json:"type"`
        Settings []interface{} `json:"settings"`
}

func main() {
        settings := []interface{}{
              "setting1", 
              "setting2", 
              "setting3",
              []string{"option1", "option2"},
        }

        c := &Config{"val1", "val2", "val3", settings}

        j, err := json.Marshal(c)
        if err != nil {
                panic(err)
        }

        fmt.Println(string(j))
}

Playground: https://go.dev/play/p/8LPAVBPmd8w

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

1 Comment

FYI: You can use "MarshalIndent()" instead of "Marshal()" to output indented json.

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.