GO JsonStr 2 obj

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.