63_json解析成map格式

package main

import (
"encoding/json"
"fmt"
)

func main() {
//json文本
JsonBuff := `
{
"Name":"steven",
"Subject":[
"C++",
"Go",
"Python"
],
"Isok":true,
"Price":66.66
}
`
m := make(map[string]interface{}, 4)
err := json.Unmarshal([]byte(JsonBuff), &m)
if err != nil {
fmt.Println("err=", err)
return
}
fmt.Println(m)
//map[Subject:[C++ Go Python] Isok:true Price:66.66 Name:steven]

//如何提取map中的数据

//
// str = string(m["Name"])//无法转换
// fmt.Println("str=", str)

//使用类型断言,进行提取map里面的数据
var str string
for key, value := range m {
switch data := value.(type) { //返回value 的值data

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]的值类型为slice,value=%v\n", key, data)

}
}

}

猜你喜欢

转载自www.cnblogs.com/zhaopp/p/11626083.html