【问题标题】:How to make dynamic JSON如何制作动态 JSON
【发布时间】:2019-07-25 11:35:33
【问题描述】:

假设 JSON 最初看起来像:

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

我想使用循环在运行时将下面的 json 附加到 jsonDatacontents 字段:

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

【问题讨论】:

  • 在 Golang 中查找地图和切片,然后查找 json.Unmarshal
  • @Seaskyways 你能用代码简要解释一下吗?因为我是 Golang 新手
  • 大多数基本问题都在Tour of Go 中得到解答,只需几分钟即可完成。

标签: json go dynamic


【解决方案1】:

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

但是 Go 提供了一个内置的 json 包,可以简化流程。

你应该知道在 Go 中使用 JSON 的 3 件事,并且你可以更进一步......

  1. Go 切片被转换为 JSON 数组 ([]interface{})
  2. Go 地图被转换为 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 and Go”文档https://blog.golang.org/json-and-go

    【讨论】:

    • 这与问题无关。请不要随意给出参差不齐的答案。
    猜你喜欢
    • 2020-08-19
    • 2020-01-17
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多