将接口数组转换为映射数组的最佳方法是什么?

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

What is the best way to convert array of interface into array of map in golang?

问题

我已经创建了一个Web服务器,该服务器能够接收POST请求。然而,当我在POST数据中发送map[string]string数组时,服务器将其接收为interface{}数组。我该如何将其转换回map[string]string数组?

例如:当我在POST请求中发送以下示例时,

params : [{"name" : "shail", "age" : 24}]

我将params发送为

[](map[string]string)

但是当服务器接收到这个数据时,它将params视为

[]interface{}

我该如何将params赋值给由

[](map[string]interface{})

定义的变量?

英文:

I've created a web server and this server is able to get POST request. However, when I send array of map[string]string in POST data, server receives it as array of interface{}. How can I convert it back to array of map[string]string?

Example : Like when I send following example in POST request,

params : [{"name" : "shail", "age" : 24}]

I'm sending params as

[](map[string]string)

but when server receives this data, it treats params as

[]interface{}

.How do I assign params in a variable defined by

[](map[string]interface{})

?

答案1

得分: 1

你可以对值进行类型断言来完成最简单的操作:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var source []interface{}
	var test = make(map[string]string, 0)
	test["hello"] = "World"
	source = append(source, test)
	var dest = source[0].(map[string]string)
	fmt.Println(reflect.TypeOf(dest).Kind())
	fmt.Println(dest["hello"])
}

这段代码的作用是将一个map[string]string类型的值存储到一个[]interface{}类型的切片中,并通过类型断言将其取出并赋值给dest变量。然后打印出dest的类型和键值对中键为"hello"的值。

英文:

The easiest thing you can do is a type assertion on the values:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var source []interface{}
	var test = make(map[string]string, 0)
	test["hello"] = "World"
	source = append(source, test)
	var dest = source[0].(map[string]string)
	fmt.Println(reflect.TypeOf(dest).Kind())
	fmt.Println(dest["hello"])
}

huangapple
  • 本文由 发表于 2015年8月30日 06:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/32291185.html
匿名

发表评论

匿名网友

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

确定