I have a JSON object similar to this one:
{
"name": "Cain",
"parents": {
"mother" : "Eve",
"father" : "Adam"
}
}
Now I want to parse “name” and “mother” into this struct:
struct {
Name String
Mother String `json:"???"`
}
I want to specify the JSON field name with the json:... struct tag, however I don’t know what to use as tag, because it is not the top object I am interested in. I found nothing about this in the encoding/json package docs nor in the popular blog post JSON and Go. I also tested mother, parents/mother and parents.mother.
Unfortunately, unlike
encoding/xml, thejsonpackage doesn’t provide a way to access nested values. You’ll want to either create a separate Parents struct or assign the type to bemap[string]string. For example:You could then provide a getter for mother as so:
This may or may not play into your current codebase and if refactoring the
Motherfield to a method call is not on the menu, then you may want to create a separate method for decoding and conforming to your current struct.