user3080873 user3080873 - 2 months ago 10
JSON Question

Golang json.Unmarshal not returning decoded data

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

Amd Amd
Answer

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