go操作json,注意json的嵌套、數組

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

package main

import (

"encoding/json""fmt""os"

)

type ConfigStruct struct {

Host              string   `json:"host"`Port              int      `json:"port"`AnalyticsFile     string   `json:"analytics_file"`StaticFileVersion int      `json:"static_file_version"`StaticDir         string   `json:"static_dir"`TemplatesDir      string   `json:"templates_dir"`SerTcpSocketHost  string   `json:"serTcpSocketHost"`SerTcpSocketPort  int      `json:"serTcpSocketPort"`Fruits            []string `json:"fruits"`

}

type Other struct {

SerTcpSocketHost string   `json:"serTcpSocketHost"`SerTcpSocketPort int      `json:"serTcpSocketPort"`Fruits           []string `json:"fruits"`

}

type Object []interface{}

func main() {

jsonStr := `{"host": "http://localhost:9090","port": 9090,"analytics_file": "","static_file_version": 1,"static_dir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}`jsonStr = `{"accessToken":"507b5e08ee444dck887b66bd08672905","clientToken":"64e3a5415bfe405d9485f1jf2ea5c68e","selectedProfile":{"id":"selID","name":"Bluek404"},"availableProfiles":[{"id":"測試ava","name":"Bluek404"}]}`//json str 轉mapvar dat map[string]interface{}if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil {    fmt.Println("==============json str 轉map=======================")    fmt.Println(dat)    mapTmp := dat["selectedProfile"].(map[string]interface {})    fmt.Println(mapTmp["id"])    /*    var dat2 map[string]interface{}    if err := json.Unmarshal([]byte(jsonStr), &dat2); err == nil {        fmt.Println( dat2["firstName"])    }    */    mapTmp2 := (dat["availableProfiles"].([]interface {}))[0].(map[string]interface {})    //mapTmp3 := mapTmp2[0].(map[string]interface {})    fmt.Println(mapTmp2["id"])}//json str 轉structvar config ConfigStructif err := json.Unmarshal([]byte(jsonStr), &config); err == nil {    fmt.Println("================json str 轉struct==")    fmt.Println(config)    fmt.Println(config.Host)}//json str 轉struct(部份欄位)var part Otherif err := json.Unmarshal([]byte(jsonStr), &part); err == nil {    fmt.Println("================json str 轉struct==")    fmt.Println(part)    fmt.Println(part.SerTcpSocketPort)}//struct 到json strif b, err := json.Marshal(config); err == nil {    fmt.Println("================struct 到json str==")    fmt.Println(string(b))}//map 到json strfmt.Println("================map 到json str=====================")enc := json.NewEncoder(os.Stdout)enc.Encode(dat)//array 到 json strarr := []string{"hello", "apple", "python", "golang", "base", "peach", "pear"}lang, err := json.Marshal(arr)if err == nil {    fmt.Println("================array 到 json str==")    fmt.Println(string(lang))}//json 到 []stringvar wo []stringif err := json.Unmarshal(lang, &wo); err == nil {    fmt.Println("================json 到 []string==")    fmt.Println(wo)}

}

相關文章

聯繫我們

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