Skip to content

Unmarshal doesn't work for json keys with _ #498

@kubaugustyn

Description

@kubaugustyn

Hi, so it seems that Unmarshal won't work with JSON keys, that have underscores. Here's some code:

package main

import (
	"bytes"
	"fmt"

	"github.com/spf13/viper"
)

type ConfigUnderscores struct {
	FooBar string `json:"foo_bar"`
}

type Config struct {
	FooBar string `json:"fooBar"`
}

var content1 = []byte(`
{
	"foo_bar": "foo"
}`)

var content2 = []byte(`
{
	"fooBar": "foo"
}`)

func main() {
	var c1 ConfigUnderscores
	var c2 Config

	viper.SetConfigType("json")
	viper.ReadConfig(bytes.NewReader(content1))

	viper.Unmarshal(&c1)
	fmt.Printf("ConfigUnderscores: %v\n", c1)

	viper.ReadConfig(bytes.NewReader(content2))
	viper.Unmarshal(&c2)
	fmt.Printf("Config: %v\n", c2)
}

Output:

ConfigUnderscores: {}
Config: {foo}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions