首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Golang中获取JSON唯一字段名和深度嵌套的子字段值?

如何在Golang中获取JSON唯一字段名和深度嵌套的子字段值?
EN

Stack Overflow用户
提问于 2018-06-30 07:37:08
回答 1查看 823关注 0票数 1

我有一个json文件,如下所示

代码语言:javascript
复制
{
  "links": {
    "uniqueurl_1": {
      "a": {
        "b": [
          "stuff"
        ],
        "I": {
          "want": {
            "to": "morestuff",
            "go": {
              "in": {
                "here": {
                  "and": "array",
                  "itis": {
                    "very": "string",
                    "deep": "stringIwant"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

我希望获得深度(每个链接总是不同的),还希望获得“uniqueurl_1”字段的值("stringIwant")。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-30 07:57:42

在您的JSON中缺少左大括号。这样试一试:

代码语言:javascript
复制
{
  "links": {
    "uniqueurl_1": {
      "a": {
        "b": [
          "stuff"
        ],
        "I": {
          "want": {
            "to": "morestuff",
            "go": {
              "in": {
                "here": {
                  "and": "array",
                  "itis": {
                    "very": "string",
                    "deep": "stringIwant"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

并使用以下代码访问您的数据:

代码语言:javascript
复制
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"`
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51110538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档