Home > Article > Backend Development > How to Flatten Embedded Anonymous Structs in JSON with Go?
Flattening Embedded Anonymous Structs in JSON with Go
In the provided code, the MarshalHateoas function attempts to flatten the JSON representation of a struct by embedding an anonymous struct as a member of the Hateoas struct. However, the anonymous member's fields are being treated as separate named fields, leading to undesirable JSON output.
To resolve this issue, the reflect package can be leveraged to loop over the fields of the embedded struct and manually map them to a flattened representation. Here's a modified version of MarshalHateoas:
<code class="go">import ( "encoding/json" "fmt" "reflect" ) // ... func MarshalHateoas(subject interface{}) ([]byte, error) { links := make(map[string]string) // Retrieve the unexported fields of the subject struct subjectValue := reflect.Indirect(reflect.ValueOf(subject)) subjectType := subjectValue.Type() // Iterate over the fields of the embedded anonymous struct for i := 0; i < subjectType.NumField(); i++ { field := subjectType.Field(i) name := subjectType.Field(i).Name jsonFieldName := field.Tag.Get("json") // Exclude fields with "-" JSON tag if jsonFieldName == "-" { continue } // Add field values to the flattened map links[jsonFieldName] = subjectValue.FieldByName(name).Interface().(string) } // Return the JSON-encoded map return json.MarshalIndent(links, "", " ") }</code>
By replacing the anonymous member with a dynamically constructed map, the MarshalHateoas function now correctly flattens the JSON output:
<code class="json">{ "id": 123, "name": "James Dean", "_links": { "self": "http://user/123" } }</code>
This solution allows for the creation of flattened JSON representations from structs with embedded anonymous members without introducing new fields or relying on platform-specific or library-dependent tricks.
The above is the detailed content of How to Flatten Embedded Anonymous Structs in JSON with Go?. For more information, please follow other related articles on the PHP Chinese website!