Viper: Unmarshal Ingnores JSON Field Tags

Created on 13 Oct 2016  Â·  2Comments  Â·  Source: spf13/viper

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}]}]

Most helpful comment

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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kubaugustyn picture kubaugustyn  Â·  3Comments

jeffwillette picture jeffwillette  Â·  5Comments

xh3b4sd picture xh3b4sd  Â·  6Comments

Giri4joyz picture Giri4joyz  Â·  3Comments

kwk picture kwk  Â·  5Comments