登录
首页 >  Golang >  Go问答

提取Golang中嵌套JSON特定对象

来源:stackoverflow

时间:2024-03-06 13:57:25 346浏览 收藏

本篇文章向大家介绍《提取Golang中嵌套JSON特定对象》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

在 go 中使用静态属性名称解组大型 json 的特定部分的最佳实践是什么?

我的 json 映射看起来像

{
    "top_view" : {
       "@self" : "https://generic.com",
           "graph" : {
              "nodes" : [ { } ],
              "relations" : [ { } ]
                     },
         "view_status" : {}
                 }
}

我只需要检索 nodes 数组

这是我到目前为止所得到的,

https://play.golang.org/p/btfrojegquu

我只知道如何解组 nodes 部分,但我不知道如何告诉 go 开始仅解组该对象,因此如果我提供整个 json 树,代码将无法工作。 请指教,谢谢!


解决方案


这是一种方法: 定义一个显示节点路径的结构体。您可以跳过 json 中不感兴趣的成员。例如:

type whole struct {
    topview struct {
        self  string `json:"@self"`
        graph struct {
            nodes []node `json:"nodes"`
        } `json:"graph"`
    } `json:"top_view"`
}

然后编组节点

var whole whole

err := json.unmarshal([]byte(jsonresp), &whole)

这是工作代码: https://play.golang.org/p/5WvPocce_vh

您可以解组任何 json 数据,而无需在 go 代码中定义任何具体类型。使用 type 断言 type switch 来钻取刚刚解组的数据。

下面是使用上述概念的问题的工作示例。您可能需要根据您的要求进一步完善此基础,但基本概念保持不变:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

func main() {
    jsonResponse := `{
        "top_view" : {
           "@self" : "https://generic.com",
               "graph" : {
                  "nodes" : [ {
                    "@self" : "https://generic.com:443",
                    "id" : "1;;45d554600be28ee49c99d26e536225ea;;461ff354437881f6b5973d4af366b91c;;4c0f2cc8e29a4fe09240b2a0c311508d",
                    "ci" : {
                       "id" : "4c0f2cc8e29a4fe09240b2a0c311508d",
                       "name" : "NOICE",
                       "type" : "ci_collection",
                       "type_label" : "CiCollection",
                       "icon" : "/logical_group_32.svg"
                    },
                    "has_children" : true
                 }, {
                    "@self" : "https://generic.com:443hjkhk",
                    "id" : "1;;45d554600be28ee49c99d26e536225ea;;4e22910a478bf6939aed36fef22dc79e;;4a7788eeecbbeee3a8bb3189ba67f269",
                    "ci" : {
                       "id" : "4a7788eeecbbeee3a8bb3189ba67f269",
                       "name" : "NOTNOICE",
                       "type" : "ci_collection",
                       "type_label" : "CiCollection",
                       "icon" : "/logical_group_32.svg"
                    },
                    "has_children" : true
                 }, {
                    "@self" : "https://generic.com:443/fghfgh",
                    "id" : "1;;45d554600be28ee49c99d26e536225ea;;461ff354437881f6b5973d4af366b91c;;4c0f2cc8e29a4fe09240b2a0c311508d;;40b8b314821d01ac874f7209c228ab8f",
                    "ci" : {
                       "id" : "40b8b314821d01ac874f7209c228ab8f",
                       "name" : "NOICE",
                       "type" : "ci_collection",
                       "type_label" : "CiCollection",
                       "icon" : "/logical_group_32.svg"
                    },
                    "has_children" : true
                 }, {
                    "@self" : "https://generic.com:443/gfhgh",
                    "id" : "1;;45d554600be28ee49c99d26e536225ea;;4a208e0deee006668bb3cfab6541a869;;4bd30d48bc1c81b398e17435ba519f2d;;4a1c671cefd3b5b9931b4312382ff2e4",
                    "ci" : {
                       "id" : "4a1c671cefd3b5b9931b4312382ff2e4",
                       "name" : "AAA",
                       "type" : "ci_collection",
                       "type_label" : "CiCollection",
                       "icon" : "/logical_group_32.svg"
                    },
                    "has_children" : true
                 } ],
                  "relations" : [ { } ]
                         },
             "view_status" : {}
                     }
    }`

    var res interface{}
    err := json.Unmarshal([]byte(jsonResponse), &res)
    if err != nil {
        log.Fatal(err)
    }

    parseArbitoryJSONObject(res)
}

func parseArbitoryJSONObject(jsonObject interface{}) {
    data := jsonObject.(map[string]interface{})

    for k, v := range data {
        switch val := v.(type) {
        case string:
            fmt.Println(k, "is string:", val)
        case float64:
            fmt.Println(k, "is float64", val)
        case bool:
            fmt.Println(k, "is boolean", val)
        case []interface{}:
            fmt.Println(k, "is an array:")
            for i, u := range val {
                fmt.Println(i, u)
            }
        case map[string]interface{}:
            fmt.Println(k, "is an map[string]interface{}:")
            parseArbitoryJSONObject(val)
        default:
            fmt.Println(k, "is of a type I don't know how to handle")
        }
    }
}

这里 json.unmarshal 使用 empty 接口 ,它可以保存任何值。函数 parsearbitoryjsonobject() 使用 type 断言 来方便从未整理的数据中提取值。

type 开关 中,您可能需要进一步放置或修改逻辑以从未编组的 json 对象中获取所需的项目。

下面是go-演示代码片段链接供您参考:

https://play.golang.org/p/VUJsSXxSfVG

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>