英文:
How can I push value into nested map[string]interface{} slice?
问题
这是一个示例:https://play.golang.org/p/aQXJzH6Yjo
i := make(map[string]interface{})
i["some"] = []interface{}{
[]interface{}{1, 2, "3--"},
map[string]interface{}{
"value": "some",
},
}
我如何将额外的值添加到[]interface{}{1, 2, "3--"}
切片中?我基本上需要创建一个可以转换为JSON的任意数据结构。我查看了https://github.com/Jeffail/gabs,但似乎不允许创建嵌套数组。
英文:
Here is an example: https://play.golang.org/p/aQXJzH6Yjo
i := make(map[string]interface{})
i["some"] = []interface{}{
[]interface{}{1, 2, "3--"},
map[string]interface{}{
"value": "some",
},
}
How can I push additonal value into []interface{}{1, 2, "3--"}
slice? I basically need to create arbitrary datastructure that will be transformed into json. Looked into https://github.com/Jeffail/gabs , but it doesn't seem to allow create nested arrays
答案1
得分: 3
这是一个有点凌乱的代码示例,但你可以按照这里的方式进行操作(我省略了错误处理):https://play.golang.org/p/JgZ4fAgRAz
i := make(map[string]interface{})
i["some"] = []interface{}{
[]interface{}{1, 2, "3--"},
map[string]interface{}{
"value": "some",
},
}
fmt.Println(i)
var myval []interface{} = i["some"].([]interface{})
var mylist []interface{} = myval[0].([]interface{})
mylist = append(mylist, "Another value")
// 将可能是新切片的元素 0 替换回去
myval[0] = mylist
// 不需要写回到 map 中 - 切片是引用类型
fmt.Println(i)
希望对你有帮助!
英文:
It's a little messy, but you can do it as shown here (I've left out the error handling): https://play.golang.org/p/JgZ4fAgRAz
i := make(map[string]interface{})
i["some"] = []interface{}{
[]interface{}{1, 2, "3--"},
map[string]interface{}{
"value": "some",
},
}
fmt.Println(i)
var myval []interface{} = i["some"].([]interface{})
var mylist []interface{} = myval[0].([]interface{})
mylist = append (mylist, "Another value")
// Replace the potentially new slice into element 0
myval[0] = mylist
// No need to write back to the map - the slice is a reference type
fmt.Println(i)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论