dpiw16824 2017-08-17 12:21
浏览 30
已采纳

在Go中解组JSON结构以生成空地图

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...
  • 写回答

1条回答 默认 最新

  • duandao1931 2017-08-17 12:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器