英文:
Best way to store/decode json inside struct mapping
问题
我有一个结构体内部的映射,如下所示:
type Red struct {
**other
Tel map[string]string `json:"Tel"`
}
我以以下方式接收格式化为 JSON 的数据:
{
"Params": [
{"rewew": "tref"},
{"Value": "x"},
....
]
}
我正在寻找一种最有效的方法来使用这些数据填充我的结构体,以便实现以下效果:
Tel["rewew"] = "tref"
Tel["Value"] = "x"
对于其他值,当这些值是简单值时,它们可以正常工作,例如:
var t Red
decode := json.NewDecoder(req.Body)
decode.Decode(&t)
但是我在处理映射时遇到了问题。
英文:
I have a mapping inside a struct as follow :
type Red struct {
**other
Tel map[string]string `json:"Tel"`
}
I receive my data json formated the following way
{
"Params":[{"rewew": "tref"},{"Value": "x"},....]
}
And i'm searching for the most effective way of populating my struct with the data so that
Tel["rewew"] = "tref"
Tel["Value"] = "x"
For the rest of the values it works fine when those are simplier values when doing this:
var t Red
decode := json.NewDecoder(req.Body)
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
{
"Params":[{"rewew": "tref"},{"Value": "x"},....]
}
And if you want to map Params
into Tel
, your structure should be:
type Red struct {
**other
Tel []map[string]string `json:"Params"`
}
And you can add new elements like:
red.Tel = append(red.Tel, map[string]string{"rewew": "tref"})
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
{
"Params":{"rewew": "tref", "Value": "x"}
}
The struct should be:
type Red struct {
**other
Tel map[string]string `json:"Params"`
}
and you can use the data like:
red.Tel["rewew"] = "tref"
red.Tel["Value"] = "x"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论