【问题标题】:Golang iterate over nested structGolang 遍历嵌套结构
【发布时间】:2021-12-24 16:01:42
【问题描述】:

我想在 golang 中迭代一个嵌套的 json 结构。问题是,我不完全知道结构的嵌套程度,因为有多个 json。在这种情况下,例如输出应该是: “可用”:假 “类型”:“富” “名称”:“富” “街”:“富” ....

这可能吗?

{
    "informations": {
        "available": false,
        "provide": {
            "informations": {
                "customer": {
                    "type": "foo",
                    "address": {
                        "name": "foo",
                        "street": "foo",
                        "zipcode": "123",
                        "city": "foo"
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 你试过什么?你有什么问题?发布您的尝试,minimal reproducible example
  • 非常喜欢。我只是诚实地认为直到现在还没有那么酷。 :(
  • 通常的方法是将文档解组为(嵌套的)map[string]interface{},然后从最顶层(当然)和type-asserting 开始,基于键(或“路径”由键嵌套形成)或值上的type-switching
  • 这可以给你一些提示:play.golang.org/p/Deu7ZAdYO13>

标签: json go


【解决方案1】:

我认为您可以使用map[string]interface{} 来做到这一点。因为,正如您所说,您并不确切知道 JSON 的结构。但是,每次提取数据时,您都需要知道 JSON 结构。此外,您需要对内部map[string]interface{} 进行类型断言。对于类型断言,您可以查看here 的答案。

这是我编写的示例代码:

package main

import (
    "encoding/json"
    "fmt"
)

var j = `{
    "informations": {
        "available": false,
        "provide": {
            "informations": {
                "customer": {
                    "type": "foo",
                    "address": {
                        "name": "foo",
                        "street": "foo",
                        "zipcode": "123",
                        "city": "foo"
                    }
                }
            }
        }
    }
}`

func main() {
    var data map[string]interface{}
    err := json.Unmarshal([]byte(j), &data)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Println(data["informations"])
    information := data["informations"]
    provide := information.(map[string]interface{})["provide"]
    fmt.Println(provide)
}

输出将是:

map[available:false provide:map[informations:map[customer:map[address:map[city:foo name:foo street:foo zipcode:123] type:foo]]]]
map[informations:map[customer:map[address:map[city:foo name:foo street:foo zipcode:123] type:foo]]]

Go Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多