我得到了一个带有{{"单词名称":"单词含义"},{"单词名称":"单词含义&# 34;},...} 我想解析单词的地图。 我试着用接口{}编写代码,但我无法想象如何。谢谢你的阅读。
答案 0 :(得分:2)
如果您有办法将第一个和最后一个花括号更改为方括号,那么您可以执行以下操作:
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
var raw_list []map[string]string
var jsonText = []byte(`[
{"Cat": "small animal"},
{"Cow": "Big animal"}
]`)
err := json.Unmarshal(jsonText, &raw_list)
if err != nil {
log.Fatal(err)
}
fmt.Printf("raw_list : %s\n", raw_list)
new_map := make(map[string]string)
for _, ele := range raw_list {
for key, val := range ele {
new_map[key] = val
}
}
fmt.Printf("new_map %s\n", new_map)
}
结果:
raw_list : [map[Cat:small animal] map[Cow:Big animal]]
new_map map[Cat:small animal Cow:Big animal]
答案 1 :(得分:1)
例如:
package main
import (
"encoding/json"
"fmt"
)
var jsonText = []byte(`[
{"Name": "Cat", "Meaning": "A Cat"},
{"Name": "Dog", "Meaning": "A Dog"}
]`)
type Word struct {
Name, Meaning string
}
func main() {
var words []Word
dict := make(map[string]string)
if err := json.Unmarshal(jsonText, &words); err != nil {
fmt.Println("error:", err)
}
for _, w := range words {
dict[w.Name] = w.Meaning
}
fmt.Printf("%v", dict)
}
产地:
地图[猫:猫狗:狗]
答案 2 :(得分:0)
您的JSON应如下所示
{
"word 1": "meaning 1",
"word 2": "meaning 2"
}
要实现这一点,你可以使用类似的东西
func fixJson(s string) string {
s = strings.Replace(s, "{", "", -1)
s = strings.Replace(s, "}", "", -1)
return "{" + s + "}"
}
完整代码
package main
import (
"encoding/json"
"strings"
"fmt"
"log"
)
func fixJson(s string) string {
s = strings.Replace(s, "{", "", -1)
s = strings.Replace(s, "}", "", -1)
return "{" + s + "}"
}
func main() {
var words map[string]string
var text = `{
{"word 1": "meaning 1"},
{"word 2": "meaning 2"}
}`
var jsonText = []byte(fixJson(text))
err := json.Unmarshal(jsonText, &words)
if err != nil {
log.Fatal(err)
}
fmt.Println(words)
}