How to handle JSON dynamic key in Go

huangapple go评论69阅读模式
英文:

How to handle JSON dynamic key in Go

问题

如果我有这样的JSON:

 {"phonenumber": "3456789", "emoji": {"emoji1": "12", "emoji2": "23", ...}}

这是一个两层的JSON,其中emoji内部的键值对将会动态生成,也就是说键名是不固定的,并且键值对的数量会相应地改变。那么如何将这个JSON编组成一个Go结构体的语法是什么?

英文:

If I have json like this:

 {"phonenumber": "3456789", emoji: {"emoji1": "12", "emoji2": "23", ...}

This is two level JSON, where the key value inside emoji will be generated dynamically, it means the key name is not fixed, and the number of key value pair will changed accordingly. So what is the syntax to marshal this JSON into a Go struct?

答案1

得分: 2

使用地图:

类型 Data struct {
    PhoneNumber string            `json:"phonenumber"`
    Emoji       map[string]string `json:"emoji"`
}

playground链接

英文:

Use a map:

type Data struct {
    PhoneNumber string            `json:"phonenumber"`
    Emoji       map[string]string `json:"emoji"`
}

playground link

huangapple
  • 本文由 发表于 2014年9月23日 02:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/25981152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定