If you have a struct:
type TestContextType struct {
Provider string
ClusterLoader struct {
Projects []struct {
Number int `json:"num"`
BaseName string `json:"basename"`
Tuning string `json:"tuning"`
Templates []struct {
Number int `json:"num"`
File string `json:"file"`
} `json:"templates"`
} `json:"projects"`
}
}
And you have JSON:
{
"provider": "local",
"ClusterLoader": {
"projects": [
{
"num": 1,
"basename": "cakephp-mysql",
"tuning": "default",
"templates": [
{
"num": 1,
"file": "cakephp-mysql.json"
}
]
}
]
}
}
viper.Unmarshal the config json..
Non-matching struct field names such as Number which are tagged as num will not get any value.
Is this expected behavior?
Specifically this file becomes:
[{0 cakephp-mysql default [{0 cakephp-mysql.json}]}]
You should use the mapstructure tag instead… The json tag is used by the json package, not by viper (which in turns uses a mapstructure package to unmarshal the config map into a struct).
Replacing all json: by mapstructure: in your structure tags should solve the issue.
Besides, viper is case-insensitive, so you don't need to specify a tag when the only difference with the JSON file is the case.
Thank you @benoitmasson that works well.
Most helpful comment
You should use the
mapstructuretag instead… Thejsontag is used by thejsonpackage, not byviper(which in turns uses amapstructurepackage to unmarshal the config map into a struct).Replacing all
json:bymapstructure:in your structure tags should solve the issue.Besides,
viperis case-insensitive, so you don't need to specify a tag when the only difference with the JSON file is the case.