英文:
Golang create json array
问题
我尝试创建一个 JSON 数组。
type Data struct {
Veggies Vegetables
array array
}
type array map[string][]int
func main() {
vegetables := Vegetables{}
vegetables["Carrots"] = 21
n := array{}
n["array"] = []int{1, 1, 1}
d := Data{vegetables, n}
json.MarshalIndent(d, "", " ")
}
请解释为什么看不到数组?
英文:
I try to create json array
type Data struct {
Veggies Vegetables
array array } type array map[string] []int
func main(){
vegetables := Vegetables{}
vegetables["Carrots"] = 21
n:= array{}
n ["array"]= [] int {1, 1 ,1}
d := Data{ vegetables,n}
json.MarshalIndent(d, "", " ")}
please explain why not see the array?
答案1
得分: 0
要使用解组器(Unmarshaller),结构体的数据成员需要被导出。也就是说,它们需要被大写,否则解组器无法访问。在你的Data
结构体中将Array
大写。只有Veggies
被解组,因为它是大写的,因此被导出。
英文:
To use an Unmarshaller, the struct data members need to be exported. That is, they need to be capitalized, or the unmarshaller does not have access. Capitalize Array
in your Data
struct. Veggies
is the only one unmarshaled because it's capitalized and therefore exported.
答案2
得分: 0
上面的代码无法编译,并且类型上存在一些问题。我建议避免使用像Array这样的名称,因为可能会与语言关键字混淆,并放弃自定义类型。也许可以使用更简单的方式,像这样:
type Data struct {
Veggies map[string]int
Ints []int
}
...
j, err := json.MarshalIndent(d, "", " ")
关于json包的文档很好,你需要阅读它们。
https://golang.org/pkg/encoding/json/#Marshal
对于Go语言来说,这本书也是一个很好的入门教材:
英文:
The code above doesn't compile, but also has a few problems with the types. I'd avoid names like Array which could be confused for language keywords, and forgo the custom types. Maybe something simpler like this?
https://play.golang.org/p/OBw4gI2Zkm
type Data struct {
Veggies map[string]int
Ints []int
}
...
j, err := json.MarshalIndent(d, "", " ")
The docs for the json package are good, you need to read them.
https://golang.org/pkg/encoding/json/#Marshal
For Go, this book is also great as an introduction to the language:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论