在 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"`
}
经常检查和处理错误。 示例 JSON 有一个语法错误,已在 playground 示例中更正。
关于json - 从 Golang 中的 JSON 字符串解码 map 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567723/