您的输入是JSON http://www.json.org/细绳。在 Go 中,您可以使用encoding/json https://golang.org/pkg/encoding/json/包来解码它。
通常,当事先知道 JSON 字符串的结构时,Gostruct
可以构建对其进行建模的类型,然后您可以将其解组为该值struct
type.
如果结构未知或发生变化,您可以将其解组为类型的值interface{}
它可以是任何 JSON 数据的目标:
s := `[[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"x","y","z",[[1,2,3],[1,2,3]]]]`
var v interface{}
if err := json.Unmarshal([]byte(s), &v); err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
fmt.Printf("%#v\n", v)
输出(尝试一下去游乐场 https://play.golang.org/p/Q5w0_qabwz):
[[1 a b 2 000000 [[1 2 3] [1 2 3]] x y z [[1 2 3] [1 2 3]]]]
[]interface {}{[]interface {}{1, "a", "b", 2, "000000", []interface {}{[]interface {}{1, 2, 3}, []interface {}{1, 2, 3}}, "x", "y", "z", []interface {}{[]interface {}{1, 2, 3}, []interface {}{1, 2, 3}}}}
正如您所看到的,结果是切片的切片,其中包含不同类型的元素(JSON 数字、字符串甚至更多切片)。
这是相同的输出,添加缩进以获得更好的感觉(使用 Go 的复合文字 https://golang.org/ref/spec#Composite_literals句法):
[]interface{}{
[]interface{}{
1, "a", "b", 2, "000000",
[]interface{}{
[]interface{}{1, 2, 3},
[]interface{}{1, 2, 3}},
"x", "y", "z",
[]interface{}{
[]interface{}{1, 2, 3},
[]interface{}{1, 2, 3},
},
},
}
当然这不是很方便,因为你必须使用类型断言 https://golang.org/ref/spec#Type_assertions从该类型的“通用”值中“提取”值interface{}
,例如提取前 2 个非数组值(还打印它们的类型以进行验证):
fmt.Printf("%T %[1]v\n", v.([]interface{})[0].([]interface{})[0])
fmt.Printf("%T %[1]v\n", v.([]interface{})[0].([]interface{})[1])
Output:
float64 1
string a
值得注意的是,Go 中的 JSON 数字被解组为 type 的值float64
即使它们可以是整数(除非明确指定了另一种类型)。