Arrays 如何在golang中动态地将对象分配给切片中的字符串键?
我正在尝试从已创建的数组创建一个数组。我拥有的数组是Arrays 如何在golang中动态地将对象分配给切片中的字符串键?,arrays,go,slice,Arrays,Go,Slice,我正在尝试从已创建的数组创建一个数组。我拥有的数组是 { "id": 1, "category": "fruits", "name": "Apple", "description": "Apple is my favorite fruit." } { "id": 2, "category": "colors", "name": "Red", "description": "Red color is always charming." } { "id": 3
{
"id": 1,
"category": "fruits",
"name": "Apple",
"description": "Apple is my favorite fruit."
}
{
"id": 2,
"category": "colors",
"name": "Red",
"description": "Red color is always charming."
}
{
"id": 3,
"category": "flowers",
"name": "Lotus",
"description": "It is one of the most beautiful flowers in this world."
}
{
"id": 4,
"category": "colors",
"name": "Pink",
"description": "A romantic color, mostly liked by women."
}
{
"id": 5,
"category": "flowers",
"name": "Rose",
"description": "I love roses."
}
{
"id": 6,
"category": "fruits",
"name": "Mango",
"description": "Mango is one of my favorite fruits."
}
现在我需要创建一个数组并填充数据,如:
"elements":{
"fruits":{
0:{
"id": 1,
"category": "fruits",
"name": "Apple",
"description": "Apple is my favorite fruit."
}
1:{
"id": 6,
"category": "fruits",
"name": "Mango",
"description": "Mango is one of my favorite fruits."
}
}
"flowers":{
0:{
"id": 3,
"category": "flowers",
"name": "Lotus",
"description": "It is one of the most beautiful flowers in this world."
}
1:{
"id": 5,
"category": "flowers",
"name": "Rose",
"description": "I love roses."
}
}
"colors":{
0:{
"id": 2,
"category": "colors",
"name": "Red",
"description": "Red color is always charming."
}
1:{
"id": 4,
"category": "colors",
"name": "Pink",
"description": "A romantic color, mostly liked by women."
}
}
}
我尝试的是:
arr := make(map[string]interface{})
arrCate := make(map[string]interface{})
arrCateFlower := make(map[int]interface{})
arrCateColor := make(map[int]interface{})
arrCateFruit := make(map[int]interface{})
for index, data := range dataVals{
if(data.Category == "flower"){
arrCateFlower[index] = data
}
if(data.Category == "colors"){
arrCateColor[index] = data
}
if(data.Category == "fruits"){
arrCateFruit[index] = data
}
}
arrCate["flowers"] = arrCateFlower
arrCate["colors"] = arrCateColor
arrCate["fruits"] = arrCateFruit
arr["elements"] = arrCate
其中dataVals
包含顶部给出的未格式化数据。通过应用上述代码,我能够获得正确的输出。但我认为这不是一个有效的方法。如果我尝试像
arr := make(map[string]interface{})
arrCate := make(map[string]interface{})
for _, data := range dataVals{
arrCate[data.Category] = data
}
arr["elements"] = arrCate
然后我得到了如下结果:
"elements":{
"fruits":{
"id": 6,
"category": "fruits",
"name": "Mango",
"description": "Mango is one of my favorite fruits."
}
"flowers":{
"id": 5,
"category": "flowers",
"name": "Rose",
"description": "I love roses."
}
"colors":{
"id": 4,
"category": "colors",
"name": "Pink",
"description": "A romantic color, mostly liked by women."
}
}
循环中该特定类别的最后一个元素。我不明白如何在不使用代码中任何静态值的情况下获取数组中的所有元素
我已经花了好几个小时在这上面了。有人能告诉我我遗漏了什么吗?
我希望你能接受额外的{}
对
没有外部{}
对:
为了不只是拥有一堆链接,也为了让其他人能够轻松地批评我的解决方案,我在这里加入了代码,稍微修改了一下:
package main
import (
"fmt"
"encoding/json"
"log"
"strings"
)
var dataAsString = `` //put data between the ``
type Item struct {
Id int `json:"id"`
Category string `json:"category"`
Name string `json:"name"`
Description string `json:"description"`
}
type CategoryToItemSliceMap map[string][]Item
type CategoryToIndexItemMap map[string]map[int]Item
func main() {
// first read the data, we use a decoder as the input was given
// as a stream of seperate json objects and not a big single one.
decoder := json.NewDecoder(strings.NewReader(dataAsString))
var ourData []Item
for decoder.More() {
var it Item
err := decoder.Decode(&it)
if err != nil {
log.Fatalln(err)
}
ourData = append(ourData, it)
}
// collect items according to categories
catToItemSlice := CategoryToItemSliceMap{}
for _,v := range ourData {
catToItemSlice[v.Category] = append(catToItemSlice[v.Category],v)
}
// turn those slices into int -> Item maps so we get the index numbers
// in the encoded json
catToIndexItemMap := CategoryToIndexItemMap{}
for k,v := range catToItemSlice {
if catToIndexItemMap[k] == nil {
catToIndexItemMap[k] = map[int]Item{}
}
for index, item := range v {
catToIndexItemMap[k][index] = item
}
}
// easiest way to get the "elements: " without an additional outer {}
// brace pair
fmt.Printf("elements: ")
// We only have one json object in the output and that is a map, so we
// can use Unmarshal and don't need a streaming encoder. And get nice
// indentation with MarshalIndent.
out, err := json.MarshalIndent(catToIndexItemMap, "", " ")
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(out))
}
尝试停止使用JSON,开始使用Go类型。请去掉
接口{}
。在围棋中模仿JSON是可能的,但比必要的更难。@Volker你能粘贴一个正确的答案,我可以试试。因为我已经尝试了我能做的,哈哈。谢谢你的回应。你用了“数组”和“切片”两个词。在您的示例中没有一个数组或切片。在尝试做稍微复杂一些的事情之前,学习一些基本的数据类型可能是个好主意。@Art实际上,我得到的数据是json,我填充的数据也是json。但在golang中,我们将使用数组和切片。所以我试着显示准确的输入和输出。这就是我粘贴它的原因。谢谢@krom,让我检查一下。只需单击操场示例中的run
。Yeyyyyy!!!好男人@克罗姆,你帮我节省了很多时间。谢谢。它也在我的实际开发环境中工作。非常感谢:)注意:使用额外的映射,只是为了在输出中获取索引,可能会使它有点低效。我也有同样的问题。在处理没有外部结构的golang时,没有直接的解决方案。[]映射[string]接口{},因为我不知道将上载什么数据表的列,我不想错过任何列。