Home > Enterprise >  How to use json tags in anonymously nested struct?
How to use json tags in anonymously nested struct?

Time:07-23

I have the following anonymous struct

func wrapHal(selfHref string) interface{} {
    return struct {
        Links struct `json: "_links"`{ # does not work, returns error "expected expression"
            Self struct {
                Href string
            }
        }
    }{
        Links: struct {
            Self struct {
                Href string
            }
        }{
            Self: struct {
                Href string
            }{
                Href: selfHref,
            },
        },
    }
}

I want to know if it is possible to rename from Links to _links when I serialize to JSON using json.Marshal

Is it possible? If so, how?

CodePudding user response:

The issue is with the base structure.

    type s struct {
        Links struct {
            Self struct {
                Href string
            }
        } `json:"_links"`
    }

is the correct syntax

  •  Tags:  
  • go
  • Related