Golang 的 json 解析不同于 PHP, PHP 是弱类型的语言,json 解析的结果可以直接放到 PHP 的数组中,
Golang 需要根据json的数据结构预先定义好数据类型,这样才能存储 json 解析后的结果。
在Golang 中使用结构体(struct)和切片(slice) 来定义用于接收 json 解析结果的数据类型。
json 解析
看一个例子:
package main
import (
"encoding/json"
"fmt"
)
type Student struct{
Name string
Sex int
Height int
}
func main() {
str := `{"name": "shanhuhai", "sex": 1,"height": 175}`
student := Student{}
json.Unmarshal([]byte(str), &student)
fmt.Println(student.Name, student.Sex, student.Height)
}
可以看到字符串解析的结果被放到了自定义数据类型Student
的 student 变量中,可以通过下标获取各个字段的数据
注意:数字类型的值在json字符串中不要加引号,其他的不管是键名还是值都要加引号。
转换成json格式
student2 := Student{
"xiamingchong",
0,
175,
}
str2, err := json.Marshal(student2)
if err != nil {
fmt.Println("json parse error.")
}
fmt.Println(string(str2))
解析复杂的json 格式
Golang通过结构体和切片组合来实现复杂的json结构解析,当 json 中有键名时使用结构体,没有键名使用切片, 结构体和切片可以嵌套组合从而实现复杂的json结构
package main
import (
"encoding/json"
"fmt"
)
type Student2 struct{
Name string
Sex int
Height int
Classmate []string
}
func main() {
str3 := `{"name": "yijay", "sex": 1, "height": 178, "classmate": ["王小五", "赵小六", "白小七"]}`
student3 := Student2{}
json.Unmarshal([]byte(str3), &student3)
fmt.Println(student.Name, student.Sex, student.Height, student3.Classmate[0], student3.Classmate[1], student3.Classmate[2])
}
不用定义结构体可以解析json么?
可以安装使用这个库
go get -u github.com/tidwall/gjson
示例代码:
package main
import (
"fmt"
"github.com/tidwall/gjson"
)
func main() {
str := `{"name": "shanhuhai", "sex": 1,"height": 175, "classmate": ["王小五","赵小六","白小七"]}`
name := gjson.Get(str, "name")
classmate := gjson.Get(str, "classmate")
fmt.Println(name)
if classmate.IsArray() {
fmt.Println(classmate.Array()[0])
fmt.Println(classmate.Array()[1])
fmt.Println(classmate.Array()[2])
}
}
对于复杂的json 结构,使用这种方式来获取值,还是省不少事的。
转载请注明:大后端 » Golang json解析的用法