golang json遍历
时间: 2023-08-20 07:06:57 浏览: 271
golang遍历全盘目录,采用线程池方式,资源利用最大化,遍历速度10W文件1分钟左右
4星 · 用户满意度95%
遍历 JSON 可以使用 Go 语言内置的 encoding/json 包。
假设有以下 JSON 数据:
```json
{
"name": "John",
"age": 30,
"email": "john@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
```
可以使用以下代码遍历该 JSON:
```go
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonData := `{
"name": "John",
"age": 30,
"email": "john@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}`
var result map[string]interface{}
err := json.Unmarshal([]byte(jsonData), &result)
if err != nil {
fmt.Println("error:", err)
}
for key, value := range result {
switch valueType := value.(type) {
case string:
fmt.Println(key, "is string:", valueType)
case float64:
fmt.Println(key, "is float64:", valueType)
case map[string]interface{}:
fmt.Println(key, "is an object:")
for subKey, subValue := range valueType {
fmt.Println(subKey, ":", subValue)
}
case []interface{}:
fmt.Println(key, "is an array:")
for i, arrValue := range valueType {
fmt.Println(i, ":", arrValue)
}
default:
fmt.Println(key, "is of a different type")
}
}
}
```
输出结果为:
```
name is string: John
age is float64: 30
email is string: john@example.com
address is an object:
street : 123 Main St
city : New York
state : NY
zip : 10001
phoneNumbers is an array:
0 : map[number:555-1234 type:home]
1 : map[number:555-5678 type:work]
```
可以看到,遍历 JSON 数据需要使用类型断言,判断当前值的类型,并根据类型进行相应操作。
阅读全文