Unmarshall nested JSON Arrays in Go / Golang

情到浓时终转凉″ 提交于 2019-12-12 03:48:21

问题


Hi I have problem with unmarshalling nested JSON arrays. What struct should I create? I want to avoid using interface{} as much as possible, but I really don't know if it is possible in this case.

Json I want to unmarshall:

"[[[{\"aaa\": \"aaa\"}]]]"

and struct I want to use to unmarshall this:

type SomeStructNestedNested struct {
   Aaa string `json:"aaa"`
}
type SomeStructNested struct {
   SomeStructNestedNested []SomeStructNestedNested
}
type SomeStruct struct {
   SomeStructNested []SomeStructNested
}

Link to example: https://play.golang.org/p/owuMptNrix


回答1:


Yes the answer is just an slice of slices:

type AutoGenerated [][][]struct {
     Aaa string `json:"aaa"`
}

Well thanks to your question I've discovered a bug in this tool I always use it for Json manipulation with Go, it can save you a lot of boring time, also it's better to use ticks `` to represent json strings like here




回答2:


The problem here is that you're attempting to use structs to represent the nesting when they're actually arrays. I find the form of the json itself to be quite poor but if you're stuck with it then you have to have a 3d array for the unmarshal, using just that 'nested nested' struct type. Below is link to your play example with some crude modifications to demonstrate the point.

type SomeStructNestedNested struct {
    Aaa string `json:"aaa"`
}

jsonString := "[[[{\"aaa\": \"aaa\"}]]]"
d := [][][]SomeStructNestedNested{}
json.Unmarshal([]byte(jsonString), &d)
fmt.Printf("%v", d)

https://play.golang.org/p/88M0_UR_3_



来源:https://stackoverflow.com/questions/39902502/unmarshall-nested-json-arrays-in-go-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!