我对golang很陌生,我想制作一个json对象,如下所示:
{
"name" : "animals",
"children" : [
{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}
]
}
我想到的代码:
type Child struct {
Name string
Value int
}
type DataMap struct {
Name string
Children []Child
}
m := DataMap{"animals", [{"cat": 5 }, {"dog": 4}, {"fish":10}] }
cj, _ := json.Marshal(m)
但是我得到了错误:
syntax error: unexpected {, expecting expression
理想情况下,我想将Children
切片附加到DataMap
循环中,但我不知道该怎么做。感谢您的提示。
您误解了结构初始化语法(与许多新手一样),这是一个示例:
package main
import (
"fmt"
"encoding/json"
)
type Child struct {
Name string
Value int
}
type DataMap struct {
Name string
Children []Child
}
func main() {
m := DataMap{"animals", []Child{{"cat", 5}, {"dog", 10 } } }
cj, _ := json.Marshal(m)
fmt.Printf("%s", cj)
}
https://play.golang.org/p/qkcAzPg6sQq
循环中:
package main
import (
"fmt"
"encoding/json"
)
type Child struct {
Name string
Value int
}
type DataMap struct {
Name string
Children []Child
}
func main() {
m := DataMap{"animals", []Child{}}
for _, item := range []Child{{"cat", 5}, {"dog", 10 }} {
m.Children = append(m.Children, item)
}
cj, _ := json.Marshal(m)
fmt.Printf("%s", cj)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句