-1

I am having trouble with unmarshaling the json data read from a .json file

type redisConfig struct {
    host string
    password string
}

func loadRedisConfig() (redisConfig, error){
    b, _ := ioutil.ReadFile("config.json")
    var config redisConfig
    fmt.Println(b)
    fmt.Println(string(b))


    e := json.Unmarshal(b, &config)

    fmt.Println(e)

    fmt.Println(config)
    return config, nil;
}

The file config.json contains this:

{
  "host": "example.com",
  "password": "password"
}

I have verified that it is valid JSON using http://jsonlint.com/. Reading other similar questions here on SO I saw that the issue was invalid json, I do not think that is the case here.

Here is the output from running the code snippet:

[123 13 10 32 32 34 104 111 115 116 34 58 32 34 101 120 97 109 112 108 101 46 99 111 109 34 44 13 10 32 32 34 112 97 115 115 119 111 114 100 34 58 32 34 112 97 115 115 119 111 114 100 34 13 10 125]
{
  "host": "example.com",
  "password": "password"
}
<nil>
{ }

The config variable contains an empty struct, it should be populated with the marshaled json provided by the file and decoder

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user3080873
  • 65
  • 2
  • 9

1 Answers1

3

Unmarshal will only set exported fields of the struct.
Just make the fields public (exported):

type redisConfig struct {
    Host     string
    Password string
}

Using ioutil.ReadFile("config.json"):

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("config.json")
    if err != nil {
        panic(err)
    }
    var config redisConfig
    err = json.Unmarshal(b, &config)
    if err != nil {
        panic(err)
    }
    fmt.Println(config)
}

type redisConfig struct {
    Host     string
    Password string
}

output:

{example.com password123}

try The Go Playground:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    //The file config.json contains this:
    str := `{
  "host": "example.com",
  "password": "password123"
}`
    //b, _ := ioutil.ReadFile("config.json")
    b := []byte(str)
    var config redisConfig
    e := json.Unmarshal(b, &config)
    if e != nil {
        panic(e)
    }
    fmt.Println(config)
}

type redisConfig struct {
    Host     string
    Password string
}

output:

{example.com password123}
  • I have played around with unmarshaling from a hard coded string in the code. Thats no problem, it works great. Somehow the data its pulling from disk must be corrupt. Thats why im printing the string and the byte array it read from disk, but they both look fine. I am on windows so there may be some shenanigans due to my os? – user3080873 Sep 11 '16 at 19:43
  • Oh okay, changing the struct variables to upper case did the trick, they needed to be public. Doh! Thanks so much! – user3080873 Sep 11 '16 at 19:47