這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//project main.gopackage mainimport ("encoding/json""fmt")func main() {fmt.Println(help())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)fmt.Println("r = ", r, "err = ", err, "\n")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")}}}}func help() string {return `Go內建這樣靈活的類型系統,向我們傳達了一個很有價值的資訊:空介面是通用類型。如果要解碼一段未知結構的JSON,只需將這段JSON資料解碼輸出到一個空介面即可。在解碼JSON資料的過程中, JSON資料裡邊的元素類型將做如下轉換: JSON中的布爾值將會轉換為Go中的bool類型; 數值會被轉換為Go中的float64類型; 字串轉換後還是string類型; JSON數組會轉換為[]interface{}類型; JSON對象會轉換為map[string]interface{}類型; null值會轉換為nil`}
輸出:
Go內建這樣靈活的類型系統,向我們傳達了一個很有價值的資訊:空介面是通用類型。如果要解碼一段未知結構的JSON,只需將這段JSON資料解碼輸出到一個空介面即可。在解碼JSON資料的過程中, JSON資料裡邊的元素類型將做如下轉換: JSON中的布爾值將會轉換為Go中的bool類型; 數值會被轉換為Go中的float64類型; 字串轉換後還是string類型; JSON數組會轉換為[]interface{}類型; JSON對象會轉換為map[string]interface{}類型; null值會轉換為nilr = map[IsPublished:true Price:9.99 Sales:1e+06 Title:Go語言編程 Authors:[XuShiwei HughLv Pandaman GuaguaSong HanTuo BertYuan XuDaoli] Publisher:ituring.com.cn] err = <nil> Title is string Go語言編程Authors is an array:0 XuShiwei1 HughLv2 Pandaman3 GuaguaSong4 HanTuo5 BertYuan6 XuDaoliPublisher is string ituring.com.cnIsPublished is bool truePrice is another type not handle yetSales is another type not handle yet