如何在Golang中制作动态json

问题描述 投票:-1回答:2

假设JSON最初看起来像:

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

我想使用一个循环,以便在运行时将下面的json附加到contentsjsonData字段:

{
      "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"
            }
          }
        ]
      }
    },

最后输出如下:

jsonData := {
      "type": "text",
      "contents": [{......},{.......}]
    }
json go dynamic
2个回答
0
投票

Golang是一种静态类型语言,与Javascript(JSON中的JS代表)不同。这意味着每个变量在编译时都必须具有指定的类型,这与JSON的工作方式不完全一致。

然而Golang提供了一个内置的json包,简化了流程。

你应该知道在Go中使用JSON的3件事情,你可以推进更多...

  1. Golang切片被翻译成JSON数组([]interface{}
  2. Golang地图被翻译为JSON对象(map[string]interface{}
  3. json包完成所有(json.Marshaljson.Unmarshal

我发现如果您阅读本文,您可以了解事情是如何运作的:

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


-2
投票
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)
}

和“JSON和Go”文件https://blog.golang.org/json-and-go

© www.soinside.com 2019 - 2024. All rights reserved.