在golang中解组顶层的JSON对象。

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

Unmarshaling top-level json object in golang

问题

我正在尝试在Golang中解析一个Node的package.json文件,并且我有以下的结构体:

type packageJson struct {
    scripts         map[string]interface{} `json:"scripts"`
    dependencies    map[string]interface{} `json:"dependencies"`
    devDependencies map[string]interface{} `json:"devDependencies"`
}

当我解析package文件时,结构体没有被填充(虽然没有报错)。我怀疑这是因为content本身是一个对象(例如:{ "scripts":"...", ... }),而Unmarshal方法希望将其转换为map[string]interface{}。有没有什么建议可以解决这个问题?我尝试创建一个包装结构体并使用jpath,但没有成功。谢谢!

注意:我可以这样做

var content map[string]interface{}
...
if val, ok := content["scripts"]; !ok { ... }

但如果可能的话,我想避免这样做。

英文:

I'm trying to parse a node package.json file in golang and I've got the following struct:

type packageJson struct {
    scripts         map[string]interface{} `json:"scripts"`
    dependencies    map[string]interface{} `json:"dependencies"`
    devDependencies map[string]interface{} `json:"devDependencies"`
}

...

var content packageJson
if err := json.Unmarshal(b, &content); err != nil {
    return err
}

When I parse the package file however the struct is not being populated (not getting an error though). I suspect it is because the content is an object itself (i.e.: { "scripts":"...", ... }) and the Unmarshal method wants to convert it into a map[string]interface{}. Any suggestions how to get around this "issue"? I tried creating a wrapper struct and using jpath but to no avail. Thanks!

Note: I could do this

var content map[string]interface{}
...
if val, ok := content["scripts"]; !ok { ... }

but I'd like to avoid it if possible.

答案1

得分: 3

你应该将结构体字段设为公共的。

英文:

You should make struct fields public.

huangapple
  • 本文由 发表于 2014年11月1日 00:12:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/26678993.html
匿名

发表评论

匿名网友

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

确定