Golang创建JSON数组

huangapple go评论72阅读模式
英文:

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语言来说,这本书也是一个很好的入门教材:

http://www.gopl.io/

英文:

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:

http://www.gopl.io/

huangapple
  • 本文由 发表于 2017年2月22日 06:37:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/42379326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定