Home >Backend Development >Golang >How to Effectively Parse Complex JSON Structures in Go Using `json.Unmarshal`?

How to Effectively Parse Complex JSON Structures in Go Using `json.Unmarshal`?

Barbara Streisand
Barbara StreisandOriginal
2025-01-03 13:41:43825browse

How to Effectively Parse Complex JSON Structures in Go Using `json.Unmarshal`?

How to Parse a Complex JSON with Go Unmarshal: Unveiling the Inner Workings

The encoding/json package in Go offers the json.Unmarshal function to simplify JSON parsing tasks. However, encountering complex JSON structures can prove challenging.

Decoding into an Interface{}

For unknown JSON data, one can decode it into an interface{} using Unmarshal. This approach results in a map[string]interface{} value where keys are strings and values are interface{} types.

For instance, consider the following JSON:

{
     "k1" : "v1", 
     "k2" : "v2", 
     "k3" : 10, 
     "result" : [
                 [
                 ["v4", v5, {"k11" : "v11", "k22" : "v22"}]
                 , ... , 
                 ["v4", v5, {"k33" : "v33", "k44" : "v44"}
                 ]
                 ], 
                 "v3"
                ] 
}

The Go code to decode and access this data:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`{
       "k1" : "v1", 
       "k3" : 10,
       result:["v4",12.3,{"k11" : "v11", "k22" : "v22"}]
    }`)
    var f interface{}
    err := json.Unmarshal(b, &f)
    if err != nil {
        fmt.Println(err)
        return
    }
    m := f.(map[string]interface{})
    for k, v := range m {
        switch vv := v.(type) {
        case string:
            fmt.Println(k, "is string", vv)
        case int:
            fmt.Println(k, "is int", vv)
        case []interface{}:
            fmt.Println(k, "is an array:")
            for i, u := range vv {
                fmt.Println(i, u)
            }
        default:
            fmt.Println(k, "is of a type I don't know how to handle")
        }
    }
}

By asserting the interface type and utilizing a type switch, it's possible to navigat

The above is the detailed content of How to Effectively Parse Complex JSON Structures in Go Using `json.Unmarshal`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn