json - 从 Golang 中的 JSON 字符串解码 map 片段

标签 json go

Go by Example: JSON tutorial 之后,我看到了如何使用基本的 JSON 字符串:

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]

我想为正在解码的 str 数据对象添加一些复杂性。

也就是说,我想添加一个以一片 map 作为其值的键:

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

我的脚本现在看起来像下面的例子,然而,在我的一生中,我无法弄清楚 Response 结构中的正确语法是什么,以便获得 中的值>事件。我知道这种语法不正确:Activities []string ... 但无法破解我的方法来获取捕获我想要显示的数据的解决方案。

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
// []
// []

感谢您的帮助!

最佳答案

使用[]map[string]字符串:

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

playground example

经常检查和处理错误。 示例 JSON 有一个语法错误,已在 playground 示例中更正。

关于json - 从 Golang 中的 JSON 字符串解码 map 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567723/

相关文章:

google-app-engine - GAE Go Json-RPC调用示例

json - 有没有办法将 package.json 文件中的依赖项安装到不同的目录中?

javascript - 如何使用 jq 命令行实用程序执行 JSON 对象更新

json - Golang 不能使用 as type struct array 或 slice literal

string - 如何在 Golang 中将数字(int 或 float64)转换为字符串

logging - 在 GO 中滚动日志文件的最佳方式

javascript - 将 JSON 对象插入数组

javascript - 如何制作一个 JSON 来将 src 和 dest 地址放入其中,并且我们可以在 grunt.js 中调用该 JSON?

android - HttpUrlConnection 请求在不读取响应的情况下无法工作

go - 从 golang 中的模板创建 yaml 文件