【发布时间】:2016-01-25 18:50:52
【问题描述】:
如何使用 Go 构造和发送 JSON 数组?
例如:
{ myArray: ["one", "two", "three"] }
目前我可以得到最接近的它以这样的字符串将 JSON 发送到浏览器:
{ myArrayString: '["once", "two", "three"]' }
这不是我想要达到的目标。
【问题讨论】:
如何使用 Go 构造和发送 JSON 数组?
例如:
{ myArray: ["one", "two", "three"] }
目前我可以得到最接近的它以这样的字符串将 JSON 发送到浏览器:
{ myArrayString: '["once", "two", "three"]' }
这不是我想要达到的目标。
【问题讨论】:
像 @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。
【讨论】:
您需要import "encoding/json",然后在您的结构中使用json.Marshal。
【讨论】: