dpiw16824 2017-08-17 04: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 04: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 关于#c##的问题:treenode反序列化后获取不到上一节点和下一节点,Fullpath和Handle报错
  • ¥15 一部手机能否同时用不同的app进入不同的直播间?
  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing