登录
首页 >  Golang >  Go问答

在 Go Lang 中处理嵌套非结构化 JSON

来源:stackoverflow

时间:2024-02-20 09:09:55 491浏览 收藏

你在学习Golang相关的知识吗?本文《在 Go Lang 中处理嵌套非结构化 JSON》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我试图了解如何从 golang 中的非结构化 json 数据访问特定数据。我有以下 json,当 foo1 有一些与空的 foo2 不同的数据时,我尝试访问 material 下的“foo1”。当像 foo1 这样的对象有数据时,我还需要从同名的分类部分读取数据。例如。由于material部分下的foo1有数据,我应该已经打印material->foo1下的方法键值以及来自分类-> foo1的desc。

package main

import (
    "encoding/json"
    "fmt"
)


type new struct {
    desc string `json:"desc"`
}

func main() {
    bjson := `{ 
                "classifications": { "foo1": { "desc": "it may be possible.", "sol": "the backups.", "ref": { "sensitive information": "https://www.sensitive_information.html", "control sphere": "https://ww.example.org/data.html" },"bar1": { "desc": "the target", "sol": "should be used.", "ref": { "abc: srgery": "https://www.orp.org/" } }}, 
               
                "material": { "backup file": [],"foo1": [ { "method": "get", "info": "it is not set", "level": 1, "parameter": "", "referer": "", "module": "diq", "curl_command": "curl \"https://example.com/\"", "wsg": [ "conf-12", "o-policy" ] }],"foo2": [],"bar1": []},
         
                "anomalies": { "server error": [], "resource consumption": [] }, 
                
                "additionals": { "web technology": [], "methods": [] }, 

                "infos": { "url": "https://example.com/", "date": "thu, 08 dec 2022 06:52:04 +0000"}}}`


    
        var parseddata = make(map[string]map[string]new)
    json.unmarshal([]byte(bjson), &parseddata)
    fmt.println("output of parseddata - \n", parseddata["classifications"]["foo1"].desc)
    
    //for _, v := range parseddata["material"] {
    //  fmt.println(v)
    //}
}

如果 foo1 不为空,则预期输出:

Method is GET
desc is It may be possible.

正确答案


您可以将其解组到 map[string]interface{} 变量中,然后使用一系列类型断言来获取您想要的信息,例如:

var parseddata = make(map[string]interface{})
json.unmarshal([]byte(bjson), &parseddata)
fmt.printf("method is %s\n", parseddata["classifications"].
  (map[string]interface{})["material"].
  (map[string]interface{})["foo1"].
  ([]interface{})[0].
  (map[string]interface{})["method"].(string))

以上将输出:

method is get

这是完整的、可运行的代码版本:

package main

import (
    "encoding/json"
    "fmt"
)

type new struct {
    desc string `json:"desc"`
}

func main() {
    bjson := `{ 
                "classifications": { "foo1": { "desc": "it may be possible.", "sol": "the backups.", "ref": { "sensitive information": "https://www.sensitive_information.html", "control sphere": "https://ww.example.org/data.html" },"bar1": { "desc": "the target", "sol": "should be used.", "ref": { "abc: srgery": "https://www.orp.org/" } }}, 
               
                "material": { "backup file": [],"foo1": [ { "method": "get", "info": "it is not set", "level": 1, "parameter": "", "referer": "", "module": "diq", "curl_command": "curl \"https://example.com/\"", "wsg": [ "conf-12", "o-policy" ] }],"foo2": [],"bar1": []},
         
                "anomalies": { "server error": [], "resource consumption": [] }, 
                
                "additionals": { "web technology": [], "methods": [] }, 

                "infos": { "url": "https://example.com/", "date": "thu, 08 dec 2022 06:52:04 +0000"}}}`

    var parseddata = make(map[string]interface{})
    json.unmarshal([]byte(bjson), &parseddata)
    fmt.printf("method is %s\n", parseddata["classifications"].(map[string]interface{})["material"].(map[string]interface{})["foo1"].([]interface{})[0].(map[string]interface{})["method"].(string))
}

如果我构建这个:

go build -o example main.go

它的运行方式如下:

$ ./main
method is get

检查值是否不存在或者是否为空列表:

data := parsedData["classifications"].(map[string]interface{})["Material"].(map[string]interface{})
val, ok := data["foo2"]
if !ok {
  panic("no key foo2 in map")
}

if count := len(val.([]interface{})); count == 0 {
  fmt.Printf("foo2 is empty\n")
} else {
  fmt.Printf("foo2 has %d items", count)
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go Lang 中处理嵌套非结构化 JSON》文章吧,也可关注golang学习网公众号了解相关技术文章。

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