1

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.

morcmarc
  • 163
  • 2
  • 8

1 Answers1

3

You should make struct fields public.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • I thought visibility doesn't matter, but I guess it's because Unmarshal takes a pointer and is outside the scope. It works now! Thanks. – morcmarc Oct 31 '14 at 16:37
  • 1
    It's because un-exported fields can't be accessed by any other packages, even with reflection. – Matt Oct 31 '14 at 18:23
  • Visibility matters because unmarshaller uses reflection and just will not be able to access private fields. There is some discussion on that subject here: http://stackoverflow.com/questions/11126793/golang-json-and-dealing-with-unexported-fields – Alex Gitelman Oct 31 '14 at 20:42