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
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"