foo1 and the desc from category->foo1. packagemainimport("encoding/json""fmt"/> foo1 and the desc from category->foo1. packagemainimport("encoding/json""fmt">

Home  >  Article  >  Backend Development  >  Handling nested unstructured JSON in Go Lang

Handling nested unstructured JSON in Go Lang

WBOY
WBOYforward
2024-02-11 22:36:09975browse

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

Handling nested unstructured JSON in Go Lang is a critical task. JSON (JavaScript Object Notation) is a commonly used data exchange format, but when JSON data is nested complexly, it may become difficult to process. PHP editor Yuzai will introduce you to some methods and techniques for processing nested unstructured JSON in Go Lang to help you parse and operate this data more efficiently. By mastering these skills, you will be able to handle complex JSON data with ease, improving the readability and maintainability of your code.

Question content

I am trying to understand how to access specific data from unstructured json data in golang. I have the following json and I am trying to access "foo1" under material when foo1 has some different data than foo2 which is empty. When an object like foo1 has data, I also need to read the data from the taxonomic section with the same name. For example. Since foo1 under material section has data, I should have printed the method key value under material->foo1 and the desc from category->foo1.

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)
    //}
}

If foo1 is not empty, expected output:

Method is GET
desc is It may be possible.

Workaround

You can unmarshal it into a map[string]interface{} variable and then use a series of type assertions to get what you want Information, for example:

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))

The above will output:

method is get

This is the complete, runnable version of the code:

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))
}

If I build this:

go build -o example main.go

Here’s how it works:

$ ./main
method is get

Check if the value does not exist or is an empty list:

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)
}

The above is the detailed content of Handling nested unstructured JSON in Go Lang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete