Home  >  Article  >  Backend Development  >  How to Flatten Embedded Anonymous Structs in JSON with Go?

How to Flatten Embedded Anonymous Structs in JSON with Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 01:00:29987browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn