go 解析json 不确定类型
时间: 2023-11-27 10:03:52 浏览: 88
在 Go 中解析不确定类型的 JSON 数据可以使用 `interface{}` 类型,它可以表示任何类型的值。具体的解析过程可以按照以下步骤进行:
1. 将 JSON 数据解析为 `interface{}` 类型的变量
2. 判断该变量的类型,如果是 map 类型,则进行 map 的解析;如果是数组类型,则进行数组的解析;如果是字符串、数字等基本类型,则直接获取其值。
以下是一个示例代码,用于解析一个包含不同类型的 JSON 数据:
```go
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := `{
"name": "John",
"age": 30,
"city": "New York",
"has_car": true,
"pets": [
{"name": "Max", "type": "dog"},
{"name": "Fluffy", "type": "cat"}
]
}`
var jsonData interface{}
err := json.Unmarshal([]byte(data), &jsonData)
if err != nil {
fmt.Println(err)
return
}
jsonMap := jsonData.(map[string]interface{})
fmt.Println("Name:", jsonMap["name"])
fmt.Println("Age:", jsonMap["age"])
fmt.Println("City:", jsonMap["city"])
fmt.Println("Has car:", jsonMap["has_car"])
pets := jsonMap["pets"].([]interface{})
fmt.Println("Pets:")
for _, pet := range pets {
petMap := pet.(map[string]interface{})
fmt.Printf("\t%s (%s)\n", petMap["name"], petMap["type"])
}
}
```
在上面的代码中,我们首先将 JSON 数据解析为 `interface{}` 类型的变量 `jsonData`。然后,我们通过类型断言将其转换为 `map[string]interface{}` 类型的变量 `jsonMap`。接着,我们可以通过 `jsonMap` 中的键名来获取对应的值,其中包括字符串、数字、布尔值和数组类型。如果需要进一步解析数组类型,可以通过 `[]interface{}` 类型进行类型断言,然后再进行进一步的解析。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)