如何在Golang中制作动态json

Suppose the JSON initially looks like:

jsonData := {
  "type": "text",
  "contents": []
}

I want to use a loop in order to append the json below to the contents field of jsonData at runtime:

{
      "type": "bubble",
      "hero": {
        "size": "full"
      },
      "body": {
        "spacing": "sm",
        "contents": [
          {
            "size": "xl"
          },
          {
            "type": "box",
            "contents": [
              {
                "flex": 0
              },
              {
                "flex": 0
              }
            ]
          }
        ]
      },
      "footer": {
        "spacing": "sm",
        "contents": [
          {
            "type": "button",
            "action": {
              "type": "uri"
            }
          },
          {
            "type": "button",
            "action": {
              "type": "uri"
            }
          }
        ]
      }
    },

Finally output looks like this :

jsonData := {
      "type": "text",
      "contents": [{......},{.......}]
    }
package main

import (
    "encoding/json"
    "fmt"
)

//Member -
type Member struct {
    Name   string
    Age    int
    Active bool
}

func main() {
    // you data
    mem := Member{"Alex", 10, true}

    // JSON encoding
    jsonBytes, err := json.Marshal(mem)
    if err != nil {
        panic(err)
    }

    // JSON to string for console
    jsonString := string(jsonBytes)

    fmt.Println(jsonString)
}

and "JSON and Go" documents https://blog.golang.org/json-and-go.

Golang is a statically typed language, unlike Javascript (which JS in JSON stands for). This means that every variable has to have a specified type at the time of compilation which doesn't quite comply with how JSON works.

However Golang has provided a built-in json package which simplifies the process.

You should know 3 things to get going with JSON in Go, and you can advance more...

  1. Golang slices are translated to JSON arrays ([]interface{})
  2. Golang maps are translated to JSON objects (map[string]interface{})
  3. json package does it all (json.Marshal and json.Unmarshal)

I find if you read this article you can get an understanding of how things work:

https://www.sohamkamani.com/blog/2017/10/18/parsing-json-in-golang/
https://blog.golang.org/json-and-go