【问题标题】:Creating JSON array in Go在 Go 中创建 JSON 数组
【发布时间】:2016-01-25 18:50:52
【问题描述】:

如何使用 Go 构造和发送 JSON 数组?

例如:

{ myArray: ["one", "two", "three"] }

目前我可以得到最接近的它以这样的字符串将 JSON 发送到浏览器:

{ myArrayString: '["once", "two", "three"]' } 

这不是我想要达到的目标。

【问题讨论】:

    标签: arrays json go


    【解决方案1】:

    @swoogan cmets 一样直截了当

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type myJSON struct {
        Array []string
    }
    
    func main() {
        jsondat := &myJSON{Array: []string{"one", "two", "three"}}
        encjson, _ := json.Marshal(jsondat)
        fmt.Println(string(encjson))
    }
    

    演示可用here

    【讨论】:

      【解决方案2】:

      您需要import "encoding/json",然后在您的结构中使用json.Marshal

      https://golang.org/pkg/encoding/json/#example_Marshal

      【讨论】:

        猜你喜欢
        • 2017-07-11
        • 2019-01-05
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 2015-04-28
        • 1970-01-01
        相关资源
        最近更新 更多