gpt4 book ai didi

json - 如何在 Go1.9 中将 json 字符串解码为 sync.Map 而不是法线贴图?

转载 作者:IT王子 更新时间:2023-10-29 01:21:06 31 4
gpt4 key购买 nike

我可以像这样使用 go 语言将 json 字符串解码为映射:

func main(){
date := []byte(`{"127.1":{"host":"host1","list":["list123","list456"]},"127.2":{"host":"host2","list":["list223","list256"]}}`)
var x interface{}
json.Unmarshal(date, &x)
t := x.(map[string]interface{})
var aa []interface{}
aa = (t["127.2"].(map[string]interface{})["list"])
for _, v := range aa {
fmt.Println(v.(string))
}
}

但我想知道如何在 Go1.9 中将它解码为 sync.Map。我试了很多方法都失败了,谁能帮帮我?

我试过这样的:

    func main(){
date := []byte(`{"127.1":{"host":"host1","list":["list123","list456"]},"127.2":{"host":"host2","list":["list223","list256"]}}`)
var x interface{}
json.Unmarshal(date, &x)
t := x.((sync.Map)[string]interface{}) //compile error
}

我也这样试过:

    func main(){
date := []byte(`{"127.1":{"host":"host1","list":["list123","list456"]},"127.2":{"host":"host2","list":["list223","list256"]}}`)
var x sync.Map
json.Unmarshal(date, &x)
fmt.Println(x) // but the map has nothing
}

最佳答案

如果你需要一个片段来做另一种方式

func (f Foo) MarshalJSON() ([]byte, error) {
tmpMap := make(map[YourTypeOfKey]YourTypeOfValue)
f.Range(func(k, v interface{}) bool {
tmpMap[k.(YourTypeOfKey)] = v.(YourTypeOfValue)
return true
})
return json.Marshal(tmpMap)
}

关于json - 如何在 Go1.9 中将 json 字符串解码为 sync.Map 而不是法线贴图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390409/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com