我有一个看起来像这样的json文件

{
  "links": {
    "uniqueurl_1": {
      "a": {
        "b": [
          "stuff"
        ],
        "I": {
          "want": {
            "to": "morestuff",
            "go": {
              "in": {
                "here": {
                  "and": "array",
                  "itis": {
                    "very": "string",
                    "deep": "stringIwant"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

而且我想获取uniqueurl_1(每个链接总是不同的),并且我还想获​​取“deep”字段的值(“stringIwant”)

我知道如果嵌套的不是太深,您可以在Golang中创建一堆结构,但是当深度太深时,它仍然是唯一/最好的方法吗?

最佳答案

您的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"`
}

10-06 03:40