我不知道如何在golang中格式化结构,以便我可以获得JSON格式的地图列表(键/值对)?到目前为止,我试过这个
package main
import (
"encoding/json"
"fmt"
)
func main() {
map1 := map[string]interface{}{"dn": "abc", "status": "live", "version": 2, "xyz": 3}
map2, _ := json.Marshal(map1)
fmt.Println(string(map2))
}
Run Code Online (Sandbox Code Playgroud)
这里只是打印键/值对...
{ "DN": "ABC", "状态": "活", "版本":2, "XYZ":3}
但我需要这样的输出:
[{ "DN": "ABC", "状态": "活"},{ "版本":2, "XYZ":3}]
Ste*_*rer 12
正如@Volker所建议的,您应该使用切片地图:
package main
import (
"fmt"
"encoding/json"
)
// M is an alias for map[string]interface{}
type M map[string]interface{}
func main() {
var myMapSlice []M
m1 := M{"dn": "abc", "status": "live"}
m2 := M{"version": 2, "xyz": 3}
myMapSlice = append(myMapSlice, m1, m2)
// or you could use `json.Marshal(myMapSlice)` if you want
myJson, _ := json.MarshalIndent(myMapSlice, "", " ")
fmt.Println(string(myJson))
}
Run Code Online (Sandbox Code Playgroud)
输出:
[
{
"dn": "abc",
"status": "live"
},
{
"version": 2,
"xyz": 3
}
]
Run Code Online (Sandbox Code Playgroud)
从代码中,我使用别名map[string]interface{}来使初始化接口映射更方便.
链接到代码:https://play.golang.org/p/gu3xafnAyG