There are a few questions on the topic but none of them seem to cover my case, thus I'm creating a new one.
I have JSON like the following:
{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}
Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?
The solution I'm adopting right now is the following:
type Foo struct {
More String `json:"more"`
Foo struct {
Bar string `json:"bar"`
Baz string `json:"baz"`
} `json:"foo"`
// FooBar string `json:"foo.bar"`
}
This is a simplified version, please ignore the verbosity. As you can see, I'd like to be able to parse and assign the value to
// FooBar string `json:"foo.bar"`
I've seen people using a map, but that's not my case. I basically don't care about the content of foo
(which is a large object), except for a few specific elements.
What is the correct approach in this case? I'm not looking for weird hacks, thus if this is the way to go, I'm fine with that.
Yes. With gjson all you have to do now is:
bar := gjson.Get(json, "foo.bar")
bar
could be a struct property if you like. Also, no maps.yes you can assign the values of nested json to struct until you know the underlying type of json keys for example.
This is an example of how to unmarshall JSON responses from the Safebrowsing v4 API sbserver proxy server: https://play.golang.org/p/4rGB5da0Lt
Combining map and struct allow unmarshaling nested JSON objects where the key is dynamic. => map[string]
For example: stock.json
Go application
The dynamic key in the hash is handle a string, and the nested object is represented by a struct.
Like what Volker mentioned, nested structs is the way to go. But if you really do not want nested structs, you can override the UnmarshalJSON func.
http://play.golang.org/p/T0aZEDL0Nu
Please ignore the fact that I'm not returning a proper error. I left that out for simplicity.
What about anonymous fields? I'm not sure if that will constitute a "nested struct" but it's cleaner than having a nested struct declaration. What if you want to reuse the nested element elsewhere?