解码未知结构的JSON数据

如果要解码一段未知结构的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 main

import (
	"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 true
Price is another type not handle yet
Sales is another type not handle yet
Title is string Go语言编程
Authors is an array:
0 XuShiwei
1 HughLv
2 Pandaman
3 GuaguaSong
4 HanTuo
5 BertYuan
6 XuDaoli
Publisher is string ituring.com.cn


你可能感兴趣的:(Go)