-2

I have a json file, containing plenty of data:

{"elec":{
    "s20":{
        "coldS":{
            "wDay": {
                "Night":   {"avg": 1234, "stddev": 56},
                "Morning": {"avg": 5432, "stddev": 10}
                ...
            },
            ...
        },
        ...
    },
    ...
}

I want to load this file as a go structure:

type ConsumConfig struct {
    elec map[string]map[string]map[string]map[string]ConsumConfValue `json:"elec"`
    gas  map[string]map[string]map[string]map[string]ConsumConfValue `json:"gas"`
}

type ConsumConfValue struct {
    avg   int `json:"avg"`
    stdev int `json:"stddev"`
}

When I do unmarshaling file data, I obtain an zero-value object of my struct type instead of an object full of data (obtaining elec = map[] and gas = map[]). So when I access to the value of theses map, I obtain zero-values (so 0 cause there are integers).

There is no compilation nor execution errors. I try to find if there was a problem of filename or if my file containing zeros, but it's not; there is the file (that is successfully loaded as a byte array), containing values different than 0.

Here is my code to unmarshal the file:

func GetConsumConfig(climatFilePath string) ConsumConfig {
    fileBytes, err := ioutil.ReadFile(climatFilePath) // get file as byte array
    if err != nil {
        panic(err)
    }

    var configConsum ConsumConfig
    err = json.Unmarshal(fileBytes, &configConsum) // byte array as struct
    if err != nil {
        panic(err)
    }

    return configConsum
}

And here is the test I do to view that there is anything inside the returned object:

fmt.Println("0...", climatFilePath)
for a, b := range returnedConfigConsum.elec {
    fmt.Println(a, ": ", b)
}
fmt.Println("1...")
for a, b := range returnedConfigConsum.gas {
    fmt.Println(a, ": ", b)
}
fmt.Println("2...")

And this is printing just that:

0... file/path.json
1...
2...

Instead of something like

0... file/path.json
s20: map[..]
s50: map[..]
s75: map[..]
1...
s20: map[..]
s50: map[..]
s75: map[..]
2...
NatNgs
  • 874
  • 14
  • 25

1 Answers1

2

This is because your elec and gas fields are lowercase. json.Unmarshal will only touch the fields starting with an uppercase. Renaming them to Elec and Gas should probably fix the issue.

Constantin S. Pan
  • 1,362
  • 11
  • 4
  • Oh ok, I understand why the -1 on my question x) I'm not accustomed to that lower/uppercase changes how programs works...Thank you (I think I will delete this question soon...); Note that I have also to change `avg` and `stdev` to `Avg` and `Stdev` too (hard thing to doesn't works because of a lowercase) – NatNgs Aug 17 '17 at 12:51