如何在Golang中访问嵌套的Json键值 [英] how to access nested Json key values in Golang

查看:58
本文介绍了如何在Golang中访问嵌套的Json键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

团队,编程新手.如下图所示对Json进行编组后,我有可用数据,该数据具有嵌套的Key值.我可以访问的固定键值,如何访问嵌套键值.这是在拆封后显示的字节切片数据—>

Team, new to Programming. I have data available after unmarshaling the Json as shown below, which has nested Key values. flat key values I am able to access, how do I access nested key values. Here is the byte slice data shown below after unmarshaling —>

tables:[map[name:basic__snatpool_members] map[name:net__snatpool_members] map[name:optimizations__hosts] map[columnNames:[name] name:pool__hosts rows:[map[row:[ry.hj.com]]]] traffic_group:/Common/traffic-group-1

我可以使用以下代码访问平键值

Flat key values I am able to access by using the following code

p.TrafficGroup = m["traffic_group"].(string)

这是完整的功能

func dataToIapp(name string, d *schema.ResourceData) bigip.Iapp {
        var p bigip.Iapp

        var obj interface{}

        jsonblob := []byte(d.Get("jsonfile").(string))
        err := json.Unmarshal(jsonblob, &obj)
        if err != nil {
                fmt.Println("error", err)
        }
        m := obj.(map[string]interface{}) // Important: to access property
        p.Name = m["name"].(string)
        p.Partition = m["partition"].(string)

        p.InheritedDevicegroup = m["inherited_devicegroup"].(string)

}

推荐答案

注意:这可能不适用于您的JSON结构.我根据您的问题推断出它将是什么,但是如果没有实际的结构,我不能保证它无需修改即可工作.

Note: This may not work with your JSON structure. I inferred what it would be based on your question but without the actual structure, I cannot guarantee this to work without modification.

如果要在映射中访问它们,则需要断言从第一个映射拉出的接口实际上是一个映射.因此,您需要执行以下操作:

If you want to access them in a map, you need to assert that the interface pulled from the first map is actually a map. So you would need to do this:

tmp := m["tables"]
tables, ok := tmp.(map[string]string)
if !ok {
    //error handling here
}

r.Name = tables["name"].(string)

但是,为什么不创建与JSON输出匹配的结构,而不是将未编组的JSON作为 map [string] interface {} 来访问?

But instead of accessing the unmarshaled JSON as a map[string]interface{}, why don't you create structs that match your JSON output?

type JSONRoot struct {
    Name string `json:"name"`
    Partition string `json:"partition"`
    InheritedDevicegroup string `json:"inherited_devicegroup"`
    Tables map[string]string `json:"tables"` //Ideally, this would be a map of structs
}

然后在您的代码中:

func dataToIapp(name string, d *schema.ResourceData) bigip.Iapp {
    var p bigip.Iapp

    var obj &JSONRoot{}

    jsonblob := []byte(d.Get("jsonfile").(string))
    err := json.Unmarshal(jsonblob, &obj)
    if err != nil {
            fmt.Println("error", err)
    }

    p.Name = obj.Name
    p.Partition = obj.Partition

    p.InheritedDevicegroup = obj.InheritedDevicegroup

    p.Name = obj.Tables["name"]
}

这篇关于如何在Golang中访问嵌套的Json键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆