在Go语言中解析JSON结构会生成空映射。

huangapple go评论102阅读模式
英文:

Unmarshaling JSON structure in go make empty maps

问题

我有一个包含大量数据的 JSON 文件:

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

我想将这个文件加载为一个 Go 结构:

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"`
}

当我对文件数据进行解组时,我得到了一个零值对象而不是一个包含数据的对象(得到 elec = map[]gas = map[])。所以当我访问这些映射的值时,我得到的是零值(即 0,因为它们是整数)。

没有编译或执行错误。我尝试查找是否存在文件名问题或者我的文件是否包含零值,但事实并非如此;文件存在(成功加载为字节数组),其中包含与零不同的值。

这是我用于解组文件的代码:

func GetConsumConfig(climatFilePath string) ConsumConfig {
    fileBytes, err := ioutil.ReadFile(climatFilePath) // 将文件读取为字节数组
    if err != nil {
        panic(err)
    }

    var configConsum ConsumConfig
    err = json.Unmarshal(fileBytes, &configConsum) // 将字节数组解组为结构体
    if err != nil {
        panic(err)
    }

    return configConsum
}

这是我进行测试以查看返回的对象中是否有内容的代码:

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...")

而实际上只打印出了以下内容:

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

而不是像下面这样的内容:

0... file/path.json
s20: map[..]
s50: map[..]
s75: map[..]
1...
s20: map[..]
s50: map[..]
s75: map[..]
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...

答案1

得分: 2

这是因为你的 elecgas 字段是小写的。json.Unmarshal 只会处理以大写字母开头的字段。将它们重命名为 ElecGas 可能会解决这个问题。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月17日 20:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/45734988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定