json - 无法解组数组
问题描述
有这个json文件:
{
"colors": [
["#7ad9ab", "#5ebd90", "#41a277", "#21875e", "#713517"],
["#5ebd90", "#41a277", "#21875e", "#006d46", "#561e00"],
["#005430"]
]
}
而这段代码:
type Palette struct {
Colors []string
}
func TestStuff(t *testing.T) {
c, err := os.Open("palette.json")
if err != nil {
fmt.Printf("Error: %v", err.Error())
}
defer c.Close()
bc, _ := ioutil.ReadAll(c)
var palette []Palette //also tried with Palette
err = json.Unmarshal(bc, &palette)
if err != nil {
fmt.Printf("Error: %v \n", err.Error())
}
fmt.Printf("Data: %v", palette)
}
并不断获得:
错误:json:无法将数组解组为字符串类型的 Go struct 字段 Palette.Colors
或者如果我更改调色板类型,则类似。提示?谢谢!
解决方案
您的 JSON blob 在“colors”元素中有一个嵌套数组,因此您需要在 Palette 结构中嵌套颜色数组。将 Palette 的声明修改为 hasColors
类型[][]string
解决了这个问题:
type Palette struct {
Colors [][]string
}
推荐阅读
- javascript - 选择选项时更改必填字段形式
- odoo - 更改/修改不影响 odoo UI
- postgresql - 如何在 .innerJoin() 中使用变量?
- spring - Spring Data Cassandra:如何为具有复合主键的表定义存储库?
- angular - localhost 在 Angular 后端 api 之前附加自身
- c# - 无法弄清楚,如何安装本地 SQL Server 并获取它们的连接字符串
- angular - Angular 8 发出多个 http 请求并合并所有结果
- scala - Spark-shell -i 路径/到/文件名替代
- android-studio - Intellij IDEA 自动完成顺序
- postgresql - 在 postgres 中使用“同时创建索引”是否有助于将来插入的行免于锁定?