在结构映射中存储/解码JSON的最佳方法是什么?

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

Best way to store/decode json inside struct mapping

问题

我有一个结构体内部的映射,如下所示:

  1. type Red struct {
  2. **other
  3. Tel map[string]string `json:"Tel"`
  4. }

我以以下方式接收格式化为 JSON 的数据:

  1. {
  2. "Params": [
  3. {"rewew": "tref"},
  4. {"Value": "x"},
  5. ....
  6. ]
  7. }

我正在寻找一种最有效的方法来使用这些数据填充我的结构体,以便实现以下效果:

  1. Tel["rewew"] = "tref"
  2. Tel["Value"] = "x"

对于其他值,当这些值是简单值时,它们可以正常工作,例如:

  1. var t Red
  2. decode := json.NewDecoder(req.Body)
  3. decode.Decode(&t)

但是我在处理映射时遇到了问题。

英文:

I have a mapping inside a struct as follow :

  1. type Red struct {
  2. **other
  3. Tel map[string]string `json:"Tel"`
  4. }

I receive my data json formated the following way

  1. {
  2. "Params":[{"rewew": "tref"},{"Value": "x"},....]
  3. }

And i'm searching for the most effective way of populating my struct with the data so that

  1. Tel["rewew"] = "tref"
  2. Tel["Value"] = "x"

For the rest of the values it works fine when those are simplier values when doing this:

  1. var t Red
  2. decode := json.NewDecoder(req.Body)
  3. decode.Decode(&t)

But i'm having trouble with maps

答案1

得分: 1

如果你的JSON是这样的:

{
"Params":[{"rewew": "tref"},{"Value": "x"},....]
}

如果你想将Params映射到Tel,你的结构应该是:

type Red struct {
**其他字段
Tel []map[string]string json:"Params"
}

你可以像这样添加新元素:

red.Tel = append(red.Tel, map[string]string{"rewew": "tref"})
red.Tel = append(red.Tel, map[string]string{"Value": "x"})

但是,如果你可以改变请求的格式,并且键不会重复,我认为有一种更好的方法,可以使用以下JSON格式:

{
"Params":{"rewew": "tref", "Value": "x"}
}

结构应该是:

type Red struct {
**其他字段
Tel map[string]string json:"Params"
}

你可以这样使用数据:

red.Tel["rewew"] = "tref"
red.Tel["Value"] = "x"

英文:

If your JSON is

  1. {
  2. "Params":[{"rewew": "tref"},{"Value": "x"},....]
  3. }

And if you want to map Params into Tel, your structure should be:

  1. type Red struct {
  2. **other
  3. Tel []map[string]string `json:"Params"`
  4. }

And you can add new elements like:

  1. red.Tel = append(red.Tel, map[string]string{"rewew": "tref"})
  2. red.Tel = append(red.Tel, map[string]string{"Value": "x"})

But, I think there is a better way to do it if you're allowed to change the request AND the keys don't repeat themselves, using a JSON like

  1. {
  2. "Params":{"rewew": "tref", "Value": "x"}
  3. }

The struct should be:

  1. type Red struct {
  2. **other
  3. Tel map[string]string `json:"Params"`
  4. }

and you can use the data like:

  1. red.Tel["rewew"] = "tref"
  2. red.Tel["Value"] = "x"

huangapple
  • 本文由 发表于 2016年12月12日 10:28:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/41093398.html
匿名

发表评论

匿名网友

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

确定