回答

收藏

将 Go 地图转换为 json

技术问答 技术问答 312 人阅读 | 0 人回复 | 2023-09-12

我尝试使用encoding/jsonMarshal将 Go 地图转换为 json 字符串,但结果是空字符串。: R, s8 V4 X( w0 Q! t
这是我的代码:2 E) h* q* d* W/ K5 E' f
    6 T6 `$ |, E$ s3 l6 _. ~
  • package mainimport  "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 我的输出是:[code]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}][]
    0 J3 L+ j8 B" z* [. s. P" N7 E
我真的不知道我错在哪里。谢谢你的帮助。
1 i0 ?9 G1 w+ B! U7 S. j                                                                3 {: W2 M# s; j6 K8 t% }
    解决方案:                                                                - ]6 X& ~. w* M
                                                                如果你发现了错误,你会看到这一点:6 y0 l& c! V8 w  Q9 U5 S" A" j4 y
    jsonString,err := json.Marshal(datas)fmt.Println(err)// [] json: unsupported type: map[int]main.Foo/ U( H9 e# n5 p( d* e
问题是你不能在 JSON 使用整数作为键;这是禁止的。相反,您可以提前将这些值转换为字符串,例如strconv.Itoa.
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则