1. json转map
代码语言:javascript复制package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `{"Name":"于谦","Age":50,"Rmb":123.22,"Sex":true,"Hobby":["eat","drink"]}`
JsonBytes := []byte(jsonStr)
data_map := make(map[string]interface{})
err := json.Unmarshal(JsonBytes, &data_map)
if err!= nil{
fmt.Println("err=",err)
return
}
fmt.Println(data_map)
}
- 把json转换为结构体
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `{"Name":"于谦","Age":50,"Rmb":123.22,"Sex":true,"Hobby":["eat","drink"]}`
JsonBytes := []byte(jsonStr)
type Person1 struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
p := new(Person1)
err = json.Unmarshal(JsonBytes, &p)
if err != nil{
fmt.Println(err)
return
}
fmt.Println(*p)
}
- JSON转map切片
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr1 := `[{"age":12,"hobby":["eat","read"],"name":"王小波","rmb":2322214.14,"sex":true},{"age":19,"hobby":["run","read"],"name":"王波","rmb":2324.14,"sex":true}]`
bytes1 := []byte(jsonStr1)
i := make([]map[string]interface{}, 0)
err2 := json.Unmarshal(bytes1, &i)
if err2 != nil{
fmt.Println(err)
return
}
fmt.Println(i)
}
- JSON转结构体切片
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Person1 struct {
Name string
Age int
Rmb float64
Sex bool
Hobby []string
}
jsonStr1 := `[{"age":12,"hobby":["eat","read"],"name":"王小波","rmb":2322214.14,"sex":true},{"age":19,"hobby":["run","read"],"name":"王波","rmb":2324.14,"sex":true}]`
bytes1 := []byte(jsonStr1)
persons := make([]Person1, 0)
err4 := json.Unmarshal(bytes1, &persons)
if err4 != nil{
fmt.Println(err4)
return
}
fmt.Println(persons)
}