我有一个json文件,如下所示
{
"links": {
"uniqueurl_1": {
"a": {
"b": [
"stuff"
],
"I": {
"want": {
"to": "morestuff",
"go": {
"in": {
"here": {
"and": "array",
"itis": {
"very": "string",
"deep": "stringIwant"
}
}
}
}
}
}
}
}
}
}
我希望获得深度(每个链接总是不同的),还希望获得“uniqueurl_1
”字段的值("stringIwant")。
我知道如果它的嵌套不是太深,你可以在Golang中创建一堆结构,但是当它嵌套这么深的时候,它仍然是唯一/最好的方法吗?
发布于 2018-06-30 07:57:42
在您的JSON中缺少左大括号。这样试一试:
{
"links": {
"uniqueurl_1": {
"a": {
"b": [
"stuff"
],
"I": {
"want": {
"to": "morestuff",
"go": {
"in": {
"here": {
"and": "array",
"itis": {
"very": "string",
"deep": "stringIwant"
}
}
}
}
}
}
}
}
}
}
并使用以下代码访问您的数据:
package main
import "encoding/json"
func UnmarshalNotSoDeep(data []byte) (NotSoDeep, error) {
var r NotSoDeep
err := json.Unmarshal(data, &r)
return r, err
}
func (r *NotSoDeep) Marshal() ([]byte, error) {
return json.Marshal(r)
}
type NotSoDeep struct {
Links Links `json:"links"`
}
type Links struct {
Uniqueurl1 Uniqueurl1 `json:"uniqueurl_1"`
}
type Uniqueurl1 struct {
A A `json:"a"`
}
type A struct {
B []string `json:"b"`
I I `json:"I"`
}
type I struct {
Want Want `json:"want"`
}
type Want struct {
To string `json:"to"`
Go Go `json:"go"`
}
type Go struct {
In In `json:"in"`
}
type In struct {
Here Here `json:"here"`
}
type Here struct {
And string `json:"and"`
Itis Itis `json:"itis"`
}
type Itis struct {
Very string `json:"very"`
Deep string `json:"deep"`
}
https://stackoverflow.com/questions/51110538
复制相似问题