Go语言之json解析到map

2020-08-04  本文已影响0人  测试探索
package main

import (
    "encoding/json"
    "fmt"
)

type IT struct {
    Company string `json:"company"`
    Subjects []string `json:"subjects"`
    Isok bool  `json:"isok"`
    Price float64  `json:"price"`

}

func main() {
    jsonBuf := `
    {
        "company": "itcase",
        "subjects": [
        "go",
        "python",
        "test"
    ],
    "isok": true,
    "price": 66.66
}`


    //创建一个map
    m := make(map[string]interface{},4)
    //第二个参数要地址传递
    err := json.Unmarshal([]byte(jsonBuf),&m)

    if err != nil{
        fmt.Println("err",err)
        return
}
    fmt.Printf("m: %+v" ,m)

}

//结果
m: map[company:itcase isok:true price:66.66 subjects:[go python test]]
升级版
package main

import (
    "encoding/json"
    "fmt"
)

type IT struct {
    Company string `json:"company"`
    Subjects []string `json:"subjects"`
    Isok bool  `json:"isok"`
    Price float64  `json:"price"`

}

func main() {
    jsonBuf := `
    {
        "company": "itcase",
        "subjects": [
        "go",
        "python",
        "test"
    ],
    "isok": true,
    "price": 66.66
}`


    //创建一个map
    m := make(map[string]interface{},4)
    //第二个参数要地址传递
    err := json.Unmarshal([]byte(jsonBuf),&m)

    if err != nil{
        fmt.Println("err",err)
        return
}
    fmt.Printf("m: %+v" ,m)

    //var str string

//  类型断言
    for key,value := range m {
        fmt.Printf("%v============%v\n",key,value)
        switch data := value.(type) {
        case string :
            str := data
            fmt.Printf("map[%s]的值类型为string,内容为value = %s\n",key,str)

        case bool :
            fmt.Printf("map[%s]的值类型为bool,内容为value = %v\n",key,data)

        case float64 :
            fmt.Printf("map[%s]的值类型为float64,内容为value = %f\n",key,data)

        case []interface{} :
            fmt.Printf("map[%s]的值类型为[]string,内容为value = %v\n",key,data)
        }


    }
}

//结果
m: map[company:itcase isok:true price:66.66 subjects:[go python test]]
company============itcase
map[company]的值类型为string,内容为value = itcase
subjects============[go python test]
map[subjects]的值类型为[]string,内容为value = [go python test]
isok============true
map[isok]的值类型为bool,内容为value = true
price============66.66
map[price]的值类型为float64,内容为value = 66.660000

上一篇下一篇

猜你喜欢

热点阅读