1.json转化为结构体
package main import ( "encoding/json" "fmt" ) type goods struct { Company string `json:"company"` Isok bool `json:"isok"` Price int `json:"price"` Subject []string `json:"subject"` } func main() { jsonbuff:=`{ "company":"zhangsan", "isok":true, "price":90, "subject":["go","php","java","jscript"] }` var good goods err:=json.Unmarshal([]byte(jsonbuff),&good); if err != nil { fmt.Println(111); } slice:=good.Subject; for _,v:=range slice{ fmt.Println(v); } }
2.json转化为map
package main import ( "encoding/json" "fmt" ) func main() { jsonbuff:=`{ "company":"zhangsan", "isok":true, "price":90, "subject":["go","php","java","jscript"] }` temp:=make(map[string]interface{}) err:=json.Unmarshal([]byte(jsonbuff),&temp) if err != nil { fmt.Println("aaa") } //下面这种方式获取不到因为这个里面的是interface所有需要下面的 //slice:=temp["subject"] //t,ok:=slice.([]string) //if !ok { // fmt.Println("fail") //} //fmt.Println(t); slice := temp["subject"].([]interface{}) for _,val := range slice { fmt.Println(val) } }