您如何在Go中阅读嵌套的Json?

问题描述

我要解码以下JSON,其结构可能会有所不同,因此我不想使用结构:

{ "cabinet": "A","shelve": {"Box": "10","color": "red"} }

在Golang博客https://blog.golang.org/json)之后,我准备了以下程序来对其进行解析:

import (
    "fmt"
    "encoding/json"
)

func main() {
    fmt.Println("Hello,playground")
    
    respString := `{ "cabinet": "A","color": "red"} }`
    respBytes := []byte(respString)
    
    var f interface{}
    json.Unmarshal(respBytes,&f)   

    m := f.(map[string]interface{})

    for k,v := range m {
        switch vv := v.(type) {
        case string:
            fmt.Println(k,"is string",vv)
        case float64:
            fmt.Println(k,"is float64",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")
        }
    }   
}

但是,我想知道如何访问嵌套在“ shelve”中作为值的嵌套JSON。 到目前为止,这是输出

cabinet is string A
shelve is of a type I don't kNow how to handle

如何搁置访问内部键/值? Go中哪种策略合适?

完整的可执行代码可在https://play.golang.org/p/AVMMVQVjY__B

中找到

解决方法

JSON中的

shelve是一个对象,因此将创建一个Go地图对其进行建模:

    case map[string]interface{}:
        fmt.Println(k,"is a map:")
        for k,v := range vv {
            fmt.Println("\t",k,"=",v)
        }

此更改的输出是(在Go Playground上尝试):

cabinet is string A
shelve is a map:
     color = red
     box = 10

查看相关问题:

Accessing Nested Map of Type map[string]interface{} in Golang

Is there any convenient way to get JSON element without type assertion?

Taking a JSON string,unmarshaling it into a map[string]interface{},editing,and marshaling it into a []byte seems more complicated then it should be