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

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

Convert json in a request to array in golang

问题

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

  1. type Person struct {
  2. Name string `json:"name"`
  3. }

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

  1. import (
  2. "encoding/json"
  3. "fmt"
  4. )
  5. func main() {
  6. jsonStr := `[{"name": "Rob"}, {"name": "John"}]`
  7. var people []Person
  8. err := json.Unmarshal([]byte(jsonStr), &people)
  9. if err != nil {
  10. fmt.Println("Error:", err)
  11. return
  12. }
  13. fmt.Println(people)
  14. }

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

希望对你有帮助!

英文:

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

  1. [
  2. {"name": "Rob"},
  3. {"name": "John"}
  4. ]

I'm retrieving the json from a request:

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

How would I unmarshal this into an array?

答案1

得分: 10

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

  1. import "encoding/json"
  2. // 定义用于反序列化的类型
  3. // 你也可以使用map[string]string
  4. type User struct {
  5. // `json`结构标签将json字段名映射到实际字段名
  6. Name string `json:"name"`
  7. }
  8. // 这个函数接受一个包含JSON的字节数组
  9. func parseUsers(jsonBuffer []byte) ([]User, error) {
  10. // 创建一个空数组
  11. users := []User{}
  12. // 将JSON反序列化到数组中,这会使用结构标签
  13. err := json.Unmarshal(jsonBuffer, &users)
  14. if err != nil {
  15. return nil, err
  16. }
  17. // 数组现在已经填充了用户数据
  18. return users, nil
  19. }

以上是代码的翻译结果。

英文:

you simply use json.Unmarshal for this. Example:

  1. import "encoding/json"
  2. // This is the type we define for deserialization.
  3. // You can use map[string]string as well
  4. type User struct {
  5. // The `json` struct tag maps between the json name
  6. // and actual name of the field
  7. Name string `json:"name"`
  8. }
  9. // This functions accepts a byte array containing a JSON
  10. func parseUsers(jsonBuffer []byte) ([]User, error) {
  11. // We create an empty array
  12. users := []User{}
  13. // Unmarshal the json into it. this will use the struct tag
  14. err := json.Unmarshal(jsonBuffer, &users)
  15. if err != nil {
  16. return nil, err
  17. }
  18. // the array is now filled with users
  19. return users, nil
  20. }

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:

确定