将接收到的数据,其结构为json,输入到变量s中。
package main
import (
"encoding/json"
"fmt"
)
var s = `{
"abc": {
"a": {
"x": {"p": "val"},
"y": {"p": "msg", "b": 33.5, "ms": 0},
"z": {"p": "msg ", "b": -12, "ms": 0}
},
"b": ["x", "y", "z"],
"c": [
[69, "text_05", "m n o"],
[4, " text_02", "def"],
[1, "text_01", "abc "],
[48, " text_04 ", "jkl"],
[5, " text_03 ", " ghi"],
[82, "text_06 ", " pq r "]
]
},
"xyz": {
"z": [
[11, "aaa"],
[33, "bbb"]
]
}}`
func main() {
var f map[string]interface{}
if err := json.Unmarshal([]byte(s), &f); err != nil {
fmt.Println(err)
}
d := []string{}
for key := range f {
d = append(d, key)
}
fmt.Println(len(d)) // 2
fmt.Println(d) // [abc xyz]
for j := 0; j < len(d); j++ {
// ...
}
}
如何获取给定结构的所有键和值。得到钥匙abc和xyz。如何遍历键:a、x、y、z、p、b、c及其值?
您的任务通过映射和数组的递归遍历来解决。
此处的完整示例:https ://go.dev/play/p/B002DHUb7WF
请注意,我在其中稍微更改了您的 json,更改
xyz.z
了数组中的一个对象以显示爬虫进入数组内部。另请注意,发出键的顺序与 json 文档中键的顺序不同,因为 golang 中的映射是无序的。