我已经编写了一个go程序,用于给json作为对httpRequest的响应,但我只能以这种格式创建json:
{
"Country": [
"abc",
"def",
],
"Population": [
"8388344",
"343",
]
}
使用map [string] string动态定义内容类型。有人请帮助我以下面的格式给出json:
[
{
"Country" :"abc",
"Population" :"8388344"
},
{
"Country" : "def",
"Population" :"343"
},
...
]
请帮帮我..
答案 0 :(得分:3)
你只需要制作一个结构片。改编自doc示例:
type Tuple struct {
Country string
Population string
}
tuples := []Tuple{
{Country: "abc", Population: "1234"},
{Country: "def", Population: "567"},
}
b, err := json.Marshal(tuples)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
这会产生:
[
{"Country":"abc","Population":"1234"},
{"Country":"def","Population":"567"}
]