json,Unmarshal
时间: 2024-03-30 14:27:07 浏览: 14
`json.Unmarshal` 是 Go 语言标准库中的函数,用于将 JSON 格式的数据解析成 Go 语言的数据结构。它的函数原型如下:
```go
func Unmarshal(data []byte, v interface{}) error
```
其中,`data` 是包含 JSON 数据的字节切片,`v` 是一个指向 Go 语言数据结构的指针。该函数会将 JSON 数据解析成 Go 语言的数据结构,并将结果存储在 `v` 所指向的变量中。
例如,我们可以将以下 JSON 数据解析成 Go 语言的结构体:
```json
{
"name": "Alice",
"age": 18,
"score": [98, 99, 100]
}
```
对应的 Go 语言结构体为:
```go
type Student struct {
Name string
Age int
Score []int
}
```
我们可以使用 `json.Unmarshal` 函数将 JSON 数据解析成该结构体的实例:
```go
data := []byte(`{"name":"Alice","age":18,"score":[98,99,100]}`)
var s Student
err := json.Unmarshal(data, &s)
if err != nil {
fmt.Println("json unmarshal error:", err)
}
fmt.Println(s)
```
输出将是:
```
{Name:Alice Age:18 Score:[98 99 100]}
```
注意,`json.Unmarshal` 函数解析 JSON 数据时,会根据 Go 语言数据结构的字段名和 JSON 数据的属性名进行匹配。因此,在上面的示例中,JSON 数据中的 `"name"` 属性名会被解析成 Go 语言结构体中的 `Name` 字段。如果 JSON 数据的属性名和 Go 语言结构体的字段名不一致,可以使用 `json` 标签来进行映射。例如:
```go
type Student struct {
Name string `json:"student_name"`
Age int `json:"student_age"`
Score []int `json:"student_score"`
}
```
这样,`json.Unmarshal` 函数在解析 JSON 数据时就会使用 `"student_name"`、`"student_age"` 和 `"student_score"` 属性名分别对应 `Name`、`Age` 和 `Score` 字段。