我尝试使用 encoding/json
Marshal 将我的 Go map 转换为 json 字符串,但结果为空字符串。
这是我的代码:
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[int]Foo)
for i := 0; i < 10; i++ {
datas[i] = Foo{Number: 1, Title: "test"}
}
jsonString, _ := json.Marshal(datas)
fmt.Println(datas)
fmt.Println(jsonString)
}
我的输出是:
map[9:{1 test} 2:{1 test} 7:{1 test} 3:{1 test} 4:{1 test} 5:{1 test} 6:{1 test} 8:{1 test} 0:{1 test} 1:{1 test}]
[]
我真的不知道我错在哪里。感谢您的帮助。
最佳答案
如果你发现了错误,你会看到这个:
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
问题是你不能在 JSON 中使用整数作为键;这是被禁止的。相反,您可以预先将这些值转换为字符串,例如使用 strconv.Itoa
。
查看这篇文章了解更多详情:https://stackoverflow.com/a/24284721/2679935
关于json - 将 Go map 转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24652775/
相关文章:
javascript - 如何通过 Ajax 请求将 Select2 与 JSON 一起使用?
c# - JavaScriptSerializer.Deserialize - 如何更改字段名称
ios - 在 Swift 中将 JSON 字符串转换为 Object 的简单而干净的方法
python - 如何在 Django 中不使用模板返回 JSON?
javascript - 如何将 JSON 转换为 CSV 格式并存储在变量中
json - REST API 最佳实践 : args in query string vs in