如何使用Go语言中的JSON处理函数解析API返回的数据?

一、简介
现代的Web应用程序通常依赖于RESTful API来获取数据。很多API都会返回JSON格式的数据,因此在使用Go语言编写Web应用程序时,我们经常需要处理JSON数据。

encoding/json

二、解析API返回的JSON数据
假设我们调用了一个API,该API返回了以下JSON格式的数据:

{
   "name": "John",
   "age": 25,
   "email": "john@example.com"
}

我们可以定义一个结构体来表示这个JSON数据的结构:

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}
json.Unmarshal()
import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonData := []byte(`{
        "name": "John",
        "age": 25,
        "email": "john@example.com"
    }`)

    var person Person
    err := json.Unmarshal(jsonData, &person)
    if err != nil {
        fmt.Println("解析JSON数据失败:", err)
        return
    }

    fmt.Println("名称:", person.Name)
    fmt.Println("年龄:", person.Age)
    fmt.Println("邮箱:", person.Email)
}

输出结果为:

名称: John
年龄: 25
邮箱: john@example.com

三、处理API返回的JSON数组
有时,API返回的数据可能是一个JSON数组。例如,假设我们调用了一个返回用户列表的API,它返回了以下JSON格式的数据:

[
    {
        "name": "John",
        "age": 25,
        "email": "john@example.com"
    },
    {
        "name": "Alice",
        "age": 28,
        "email": "alice@example.com"
    }
]

我们可以定义一个与JSON数组对应的结构体切片:

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

type PersonList []Person
json.Unmarshal()
import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonData := []byte(`[
        {
            "name": "John",
            "age": 25,
            "email": "john@example.com"
        },
        {
            "name": "Alice",
            "age": 28,
            "email": "alice@example.com"
        }
    ]`)

    var personList PersonList
    err := json.Unmarshal(jsonData, &personList)
    if err != nil {
        fmt.Println("解析JSON数据失败:", err)
        return
    }

    for i, person := range personList {
        fmt.Printf("用户%d:
", i+1)
        fmt.Println("名称:", person.Name)
        fmt.Println("年龄:", person.Age)
        fmt.Println("邮箱:", person.Email)
        fmt.Println("---------")
    }
}

输出结果为:

用户1:
名称: John
年龄: 25
邮箱: john@example.com
---------
用户2:
名称: Alice
年龄: 28
邮箱: alice@example.com
---------
encoding/jsonjson.Unmarshal()