3 回答
TA贡献1877条经验 获得超6个赞
例如:
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)
}
产生:
地图[猫:一只猫狗:一只狗]
TA贡献1802条经验 获得超4个赞
您的 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)
}
- 3 回答
- 0 关注
- 161 浏览
添加回答
举报