英文:
How to convert map[string]interface{} to map[string]string
问题
我正在尝试将map[string]interface{}
转换为map[string]string
,但每次尝试时都会出现恐慌错误:
package main
import (
"encoding/json"
)
func main() {
var doc interface{}
js := `{ "id": "123", "links": { "self": "/app/123" } }`
json.Unmarshal([]byte(js), &doc)
jsonObj, _ := doc.(map[string]interface{})
myFunc_convert(jsonObj)
}
func myFunc_convert(js map[string]interface{}) {
links := js["links"].(map[string]string)
links["hi"] = "foo"
}
func myFunc_noConvert(js map[string]interface{}) {
links := js["links"]
links["hi"] = "foo"
}
如果我调用myFunc_convert
,会出现以下错误:
接口转换:interface {} 是 map[string]interface {},而不是 map[string]string
如果我调用myFunc_noConvert
,会出现以下错误:
无效操作:links["hi"](类型 interface {} 不支持索引)
我事先知道links
将是map[string]string
类型,并且我需要能够向其中添加项目。我是否遗漏了某种方法来实现这一点?
我考虑过创建一个新的map[string]string
类型的映射,然后循环遍历links
中的所有内容,并将其转换为字符串类型并放入新的映射中,但这种方法似乎有些笨拙。
有没有更好的方法来实现这个需求?
英文:
I'm trying to convert a map[string]interface{}
to map[string]string
and whenever I try I get a panic:
package main
import (
"encoding/json"
)
func main() {
var doc interface{}
js := `{ "id": "123", "links": { "self": "/app/123" } }`
json.Unmarshal([]byte(js), &doc)
jsonObj, _ := doc.(map[string]interface{})
myFunc_convert(jsonObj)
}
func myFunc_convert(js map[string]interface{}) {
links := js["links"].(map[string]string)
links["hi"] = "foo"
}
func myFunc_noConvert(js map[string]interface{}) {
links := js["links"]
links["hi"] = "foo"
}
Gives me the following error if I call myFunc_convert:
interface conversion: interface {} is map[string]interface {}, not map[string]string
If I call myFunc_noConvert I get this error:
invalid operation: links["hi"] (type interface {} does not support indexing)
I know ahead of time that links will be a map[string]string
and I need to be able to add items to it. Is there a way to do this that I'm missing?
I thought about creating a new map of type map[string]string
, then looping through everything in links and converting it to type string and putting it in the new map, but that seems clunky.
Is there a better way to do this?
答案1
得分: 2
请稍等,我会为您翻译这段代码。
英文:
Here you go:
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
var doc interface{}
js := `{ "id": "123", "links": { "self": "/app/123" } }`
if err := json.Unmarshal([]byte(js), &doc); err != nil {
log.Fatal(err)
}
jsonObj, _ := doc.(map[string]interface{})
links := myFunc(jsonObj)
links["hi"] = "foo"
fmt.Printf("%+v\n", links)
}
func myFunc(js map[string]interface{}) map[string]string {
result := map[string]string{}
links, ok := js["links"].(map[string]interface{})
if !ok {
return result
}
for k := range links {
if v, ok := links[k].(string); ok {
result[k] = v
}
}
return result
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论