如何将值推入嵌套的map[string]interface{}切片中?

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年3月11日 18:10:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/42733908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定