解码未知结构的JSON数据

来源:互联网 发布:中国对东盟投资数据 编辑:程序博客网 时间:2024/05/15 10:20

如果要解码一段未知结构的JSON,只需将这段JSON数据解码输出到一个空接口即可。在解码JSON数据的过程中,JSON数据里边的元素类型将做如下转换:

1)JSON中的布尔值将会转换为Go中的bool类型;

2)数值会被转换为Go中的float64类型;

3)字符串转换后还是string类型;

4)JSON数组会转换为[]interface{}类型;

5)JSON对象会转换为map[string]interface{}类型;

6)null值会转换为nil。


在Go的标准库encoding/json包中,允许使用map[string]interface{}和[]interface{}类型的值来分别存放未知结构的JSON对象或数组,示例代码如下:

package mainimport ("fmt""encoding/json")func main() {b := []byte(`{"Title":"Go语言编程","Authors":["XuShiwei","HughLv","Pandaman","GuaguaSong","HanTuo","BertYuan","XuDaoli"],"Publisher":"ituring.com.cn","IsPublished":true,"Price":9.99,"Sales":1000000}`)var r interface{}err := json.Unmarshal(b, &r)if err == nil {fmt.Println(r)}gobook, ok := r.(map[string]interface{})if ok {for k, v := range gobook {switch v2 := v.(type) {case string:fmt.Println(k, "is string", v2)case int:fmt.Println(k, "is int", v2)case bool:fmt.Println(k, "is bool", v2)case []interface{}:fmt.Println(k, "is an array:")for i, iv := range v2 {fmt.Println(i, iv)}default:fmt.Println(k, "is another type not handle yet")}}}}

输出结果

map[Publisher:ituring.com.cn IsPublished:true Price:9.99 Sales:1e+06 Title:Go语言编程 Authors:[XuShiwei HughLv Pandaman GuaguaSong HanTuo BertYuan XuDaoli]]IsPublished is bool truePrice is another type not handle yetSales is another type not handle yetTitle is string Go语言编程Authors is an array:0 XuShiwei1 HughLv2 Pandaman3 GuaguaSong4 HanTuo5 BertYuan6 XuDaoliPublisher is string ituring.com.cn


0 0
原创粉丝点击