go 无json结构体 解析json
package main
import (
"encoding/json"
"fmt"
)
type Contact struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Contact struct {
Home string `json:"home"`
Cell string `json:"cell"`
} `json:"contact"`
}
var JSON = `{
"name":"Gopher",
"title":"",
"contact":{
"home":"123123123",
"cell":"456456456"
}
}`
func main() {
// 解析json
// var c Contact
// err := json.Unmarshal([]byte(JSON), &c)
// if err != nil {
// fmt.Println("ERROR", err)
// return
// }
// fmt.Println(c.Contact)
// fmt.Println(c.Title)
// fmt.Println(c.Name)
// // 编码json
// data, _ := json.Marshal(c)
// fmt.Println(string(data))
// 不知道数据结构的时候解析json
var tmp map[string]interface{}
_ = json.Unmarshal([]byte(JSON), &tmp)
fmt.Println("Name:", tmp["name"])
fmt.Println("Title:", tmp["title"])
fmt.Println("Contact:", tmp["contact"])
fmt.Println("Home:", tmp["contact"].(map[string]interface{})["home"])
fmt.Println("Cell:", tmp["contact"].(map[string]interface{})["cell"])
}

浙公网安备 33010602011771号