从现在开始,努力学习吧!本文《在 Go 中如何处理嵌套的 JSON 数据?》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
我有以下 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", "shelve": {"box": "10", "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/ammmvqvjy__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?
以上就是《在 Go 中如何处理嵌套的 JSON 数据?》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
