深度嵌套的 JSON 数据能用 Go 直接解析出来吗

如题所述

用reflect是可以解析出来,但我感觉你是错用了json或者用错了json,至少value应该有名字才好解析,如果不好定名字可能说明不应该用json。
这是用reflect解析的例子

package main

import (
"encoding/json"
"fmt"
"reflect"
)

var txt = `
[
[
"define",
"a",
[
"read",
"cd"
],
[
"if",
[
"\u003e",
"a",
"cd"
],
[
"print",
"demo"
],
[
"print",
"not demo"
]
]
],
[
"say",
[
"print",
"a",
[
"save",
[
"b",
[
"x",
[
"c",
"8"
]
]
]
]
]
],
[
"print",
"fun"
]
]`

func Switch(value reflect.Value) {
kind := value.Kind()
switch kind {
case reflect.String:
fmt.Printf("string: %s\n", value.String())
case reflect.Struct:
parseStruct(value)
case reflect.Slice:
parseSlice(value)
case reflect.Interface:
v := reflect.ValueOf(value.Interface())
Switch(v)
default:
fmt.Printf("unknown type: %s\n", kind.String())
}
}

func parseSlice(value reflect.Value) {
size := value.Len()
for j := 0; j < size; j++ {
field := value.Index(j)
Switch(field)
}
}

func parseStruct(value reflect.Value) {
size := value.NumField()
for i := 0; i < size; i++ {
field := value.Field(i)
Switch(field)
}
}

func main() {
var objs []interface{}
if err := json.Unmarshal([]byte(txt), &objs); err != nil {
fmt.Println(err)
return
}
for _, obj := range objs {
Switch(reflect.ValueOf(obj))
}
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网