003_golang的json解析

來源:互聯網
上載者:User

一、

package mainimport ("os""encoding/json""fmt")type response1 struct {Page   intFruits []string}type response2 struct {Page   int      `json:"page"`Fruits []string `json:"fruits"`}func main() {bolB, _ := json.Marshal(true)fmt.Println(string(bolB))  //trueintB, _ := json.Marshal(1)fmt.Println(string(intB))  //1fltB, _ := json.Marshal(2.34)fmt.Println(string(fltB))  //2.34strB, _ := json.Marshal("gopher")fmt.Println(string(strB))  //"gopher"slcD := []string{"apple", "peach", "pear"}slcB, _ := json.Marshal(slcD)fmt.Println(string(slcB))//["apple","peach","pear"]mapD := map[string]int{"apple": 5, "lettuce": 7}mapB, _ := json.Marshal(mapD)fmt.Println(string(mapB))//{"apple":5,"lettuce":7}fmt.Println(new(response1))//&{0 []}res1D := &response1{Page:   1,Fruits: []string{"apple", "peach", "pear"}}res1B, _ := json.Marshal(res1D)fmt.Println(string(res1B))//{"Page":1,"Fruits":["apple","peach","pear"]}res2D := &response2{Page:   1,Fruits: []string{"apple", "peach", "pear"}}res2B, _ := json.Marshal(res2D)fmt.Println(string(res2B))//{"page":1,"fruits":["apple","peach","pear"]}byt := []byte(`{"num":6.13,"strs":["a","b"]}`)var dat map[string]interface{}if err := json.Unmarshal(byt, &dat); err != nil {panic(err)}fmt.Println(dat)//map[strs:[a b] num:6.13]num := dat["num"].(float64)fmt.Println(num)//6.13strs := dat["strs"].([]interface{})str1 := strs[0].(string)fmt.Println(str1)//astr := `{"page": 1, "fruits": ["apple", "peach"]}`res := response2{}json.Unmarshal([]byte(str), &res)fmt.Println(res)//{1 [apple peach]}fmt.Println(res.Fruits[0])//appleenc := json.NewEncoder(os.Stdout)d := map[string]int{"apple": 5, "lettuce": 7}enc.Encode(d)//{"apple":5,"lettuce":7}}

Reference: https://gobyexample.com/json

二、

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.