您的位置:首页 > Web前端 > JavaScript

解码未知结构的JSON数据

2015-12-06 15:29 731 查看
如果要解码一段未知结构的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: