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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?