1、json解析到map(通过类型断言,找到值和value类型)
示例:
package main import (
"encoding/json"
"fmt"
) func main() {
jsonBuf := `
{
"company": "itcast",
"subjects": [
"Go",
"C++",
"Python",
"Test"
],
"isok": true,
"price": 666.666
}` //创建一个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\n", m) var str string //类型断言, 值,它是value类型
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 []string:
fmt.Printf("map[%s]的值类型为[]string, value = %v\n", key, data)
case []interface{}:
fmt.Printf("map[%s]的值类型为[]interface, value = %v\n", key, data)
} } }
执行结果:
m = map[isok:true price:666.666 company:itcast subjects:[Go C++ Python Test]] map[company]的值类型为string, value = itcast
map[subjects]的值类型为[]interface, value = [Go C++ Python Test]
map[isok]的值类型为bool, value = true
map[price]的值类型为float64, value = 666.666000