回答

收藏

将 Go 地图转换为 json

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

我尝试使用encoding/jsonMarshal将 Go 地图转换为 json 字符串,但结果是空字符串。. g$ o; {& K0 q+ I" t
这是我的代码:$ a5 w) a% o6 o, ?8 h, C4 e

      O9 G0 F; C! M9 [# M: F0 \
  • 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}][]
    ( `( w; Y  y# Q' e
我真的不知道我错在哪里。谢谢你的帮助。
! S1 T) j  K8 o& ?                                                               
7 J' n4 x0 C# _3 N; h, `+ c8 O    解决方案:                                                                - U! m: q3 @0 b9 x5 i: j) y1 }
                                                                如果你发现了错误,你会看到这一点:7 S5 b( p$ a" \) I  m2 Q8 o
    jsonString,err := json.Marshal(datas)fmt.Println(err)// [] json: unsupported type: map[int]main.Foo
    : L$ ~; X. I9 n( @
问题是你不能在 JSON 使用整数作为键;这是禁止的。相反,您可以提前将这些值转换为字符串,例如strconv.Itoa.
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则