Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: encoding/json: Create 'unwrapped' tag to embed fields in json message #54323

Closed
CreatureDev opened this issue Aug 7, 2022 · 6 comments
Labels
Milestone

Comments

@CreatureDev
Copy link

CreatureDev commented Aug 7, 2022

Allow marshaling/unmarshaling of non-anonymous structs and interfaces to embed fields in json, equivalent to how anonymous structs are embedded

type Foo struct {
    S string
}

type Bar struct {
    I int 
    F Foo `json:",unwrapped"`
}

func main() {
    var b Bar = Bar{F: Foo{S: "abc"}, I: 123}
    e, _ := json.Marshal(b)
    fmt.Println(string(e))
}

expected output

{ "S": "abc", "I": 123}
@gopherbot gopherbot added this to the Proposal milestone Aug 7, 2022
@CreatureDev
Copy link
Author

Same behavior as the @JsonUnwrapped annotation in the jackson Java library

@wallnutkraken
Copy link

Embed the struct
https://go.dev/play/p/AFxdLF9sWLf

@CreatureDev
Copy link
Author

That doesn't work for interfaces

@CreatureDev
Copy link
Author

CreatureDev commented Aug 7, 2022

You are also unable to create an anonymous field using type parameters

type Bar interface{
}

type Foo[T Bar] struct {
    T
}

throws an error
The only viable solution would be using the proposed tag

type Foo[T Bar] struct {
    Data T `json:",unwrapped"`
}

@dsnet
Copy link
Member

dsnet commented Aug 7, 2022

Duplicate of #6213.

@dsnet dsnet closed this as completed Aug 7, 2022
@knight7024
Copy link

knight7024 commented Aug 16, 2022

hey @CreatureDev, I'm at the same problem. Did you resolve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants