英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论