在Golang中解码JSON字符串中的一组映射(maps)切片。

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

Decoding a slice of maps from a JSON string in Golang

问题

根据你提供的代码,你想要解析一个包含复杂数据结构的 JSON 字符串。具体来说,你想要解析一个包含键为 "activities",值为一个包含多个映射的切片的 JSON 对象。

为了正确解析这个 JSON 字符串,你需要对 Response 结构体进行一些修改。你可以将 Activities 字段的类型设置为 []map[string]string,表示它是一个包含多个映射的切片。每个映射都有一个键 "name" 和对应的值。

以下是修改后的代码示例:

package main

import (
    "encoding/json"
    "fmt"
)

type Response struct {
    Page       int                `json:"page"`
    Fruits     []string           `json:"fruits"`
    Activities []map[string]string `json:"activities"`
}

func main() {
    str := `{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name": "swimming"}]}`
    res := Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Page)
    fmt.Println(res.Fruits)
    fmt.Println(res.Activities)
}

这样修改后,你应该能够正确解析 activities 字段中的数据了。希望对你有帮助!

英文:

Following the Go by Example: JSON tutorial, I see how to work with a basic JSON string:

package main

import (
    "encoding/json"
    "fmt"
    )

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {
    str := `{"page": 1, "fruits": ["apple", "peach"]}`
    res := Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Page)
    fmt.Println(res.Fruits)
}

// the output looks good here:
// 1
// [apple peach]

I would like to add some complexity to the str data object that I am decoding.

Namely, I would like to add a key with a slice of maps as its value:

"activities": [{"name": "running"}, {"name", "swimming"}]

My script now looks like below example, however, for the life of me, I can not figure out what the correct syntax is in the Response struct in order to get at the values in activities. I know that this syntax isn't correct: Activities []string ... but can not hack my way towards a solution that captures the data I want to display.

package main

import (
    "encoding/json"
    "fmt"
    )

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
    Activities []string `json:"activities"`
}

func main() {
    str := `{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name", "swimming"}]}`
    res := Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Page)
    fmt.Println(res.Fruits)
    fmt.Println(res.Activities)
}

// the script basically craps out here and returns:
// 0
// []
// []

Thanks for any help!

答案1

得分: 4

使用[]map[string]string:

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
    Activities []map[string]string `json:"activities"`
}

playground示例

始终检查和处理错误。示例JSON中有一个语法错误,在playground示例中已经进行了修正。

英文:

Use []map[string]string:

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
    Activities []map[string]string `json:"activities"`
}

<kbd>playground example</kbd>

Always check and handle errors.
The example JSON has a syntax error which is corrected in the playground example.

答案2

得分: 0

我知道这是一个旧的问题,但最近我编写了一个用于从JSON输入生成精确Go类型的实用程序,在类似的情况下,你可以试试这个:https://github.com/m-zajac/json2go

对于这个特定的示例,它从JSON生成了以下Go类型:

type Object struct {
    Activities []struct {
        Name string `json:"name"`
    } `json:"activities"`
    Fruits []string `json:"fruits"`
    Page   int      `json:"page"`
}

希望对你有帮助!

英文:

I know this is an old one, but i've recently written utility for generating exact go type from json input and in similar case you could give it a spin: https://github.com/m-zajac/json2go

For this particular example it generates from json:

{&quot;page&quot;: 1, &quot;fruits&quot;: [&quot;apple&quot;, &quot;peach&quot;], &quot;activities&quot;: [{&quot;name&quot;: &quot;running&quot;}, {&quot;name&quot;: &quot;swimming&quot;}]}

go type:

type Object struct {
	Activities	[]struct {
		Name string `json:&quot;name&quot;`
	}	`json:&quot;activities&quot;`
	Fruits	[]string	`json:&quot;fruits&quot;`
	Page	int		`json:&quot;page&quot;`
}

huangapple
  • 本文由 发表于 2016年2月23日 10:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/35567723.html
匿名

发表评论

匿名网友

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

确定