将请求中的 JSON 转换为 Golang 中的数组。

huangapple go评论74阅读模式
英文:

Convert json in a request to array in golang

问题

你可以使用Go语言中的json.Unmarshal函数将JSON数组解析为结构体数组。首先,你需要定义一个与JSON结构相匹配的结构体类型,例如:

type Person struct {
    Name string `json:"name"`
}

然后,你可以使用json.Unmarshal函数将JSON数据解析为结构体数组,示例如下:

import (
    "encoding/json"
    "fmt"
)

func main() {
    jsonStr := `[{"name": "Rob"}, {"name": "John"}]`

    var people []Person
    err := json.Unmarshal([]byte(jsonStr), &people)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println(people)
}

在上面的示例中,jsonStr是你从请求中获取的JSON字符串。通过调用json.Unmarshal函数,将JSON字符串解析为people数组,其中每个元素都是Person结构体类型。最后,你可以打印出people数组来验证解析结果。

希望对你有帮助!

英文:

How can I convert a json array to an array of structs? Example:

[
  {"name": "Rob"},
  {"name": "John"}
]

I'm retrieving the json from a request:

body, err := ioutil.ReadAll(r.Body)

How would I unmarshal this into an array?

答案1

得分: 10

你可以使用json.Unmarshal来实现这个功能。示例代码如下:

import "encoding/json"

// 定义用于反序列化的类型
// 你也可以使用map[string]string
type User struct {
    // `json`结构标签将json字段名映射到实际字段名
    Name string `json:"name"`
}

// 这个函数接受一个包含JSON的字节数组
func parseUsers(jsonBuffer []byte) ([]User, error) {
    // 创建一个空数组
    users := []User{}

    // 将JSON反序列化到数组中,这会使用结构标签
    err := json.Unmarshal(jsonBuffer, &users)
    if err != nil {
        return nil, err
    }

    // 数组现在已经填充了用户数据
    return users, nil
}

以上是代码的翻译结果。

英文:

you simply use json.Unmarshal for this. Example:

import "encoding/json"


// This is the type we define for deserialization.
// You can use map[string]string as well
type User struct {

	// The `json` struct tag maps between the json name
	// and actual name of the field
	Name string `json:"name"`
}

// This functions accepts a byte array containing a JSON
func parseUsers(jsonBuffer []byte) ([]User, error) {

	// We create an empty array
	users := []User{}

	// Unmarshal the json into it. this will use the struct tag
	err := json.Unmarshal(jsonBuffer, &users)
	if err != nil {
		return nil, err
	}

	// the array is now filled with users
	return users, nil

}

huangapple
  • 本文由 发表于 2014年2月23日 22:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/21969584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定