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

empty array will be send out as null #457

Closed
ScriptType opened this issue May 29, 2024 · 3 comments
Closed

empty array will be send out as null #457

ScriptType opened this issue May 29, 2024 · 3 comments
Labels
question Further information is requested

Comments

@ScriptType
Copy link

ScriptType commented May 29, 2024

i have following type which im returning.
type InstanceArrayResponse struct {
Body []*InstanceBody
}

if the Body is now an empty array i get null as a response when testing the api.

fmt.Println(instancesResponse) //&{[]}

so &{[]} is what i`m returning in the handler but in the frontend i receive null :/

When the array is Filled with values its working as expected.

@danielgtaylor
Copy link
Owner

@ScriptType this is how the Golang JSON encoder works:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

From https://pkg.go.dev/encoding/json#Marshal

What should the default behavior be? Should it be to send no body, null, or [] / {} when the body is nil or empty?

@danielgtaylor danielgtaylor added the question Further information is requested label Jun 3, 2024
@bshtmichielsen
Copy link

Hi both I experienced a similar situation and was a little surprised too. I would have expected that if Body == nil it outputs null, however when Body contains an empty slice, I would have expected [] as output.

@ScriptType
Copy link
Author

@ScriptType this is how the Golang JSON encoder works:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

From https://pkg.go.dev/encoding/json#Marshal

What should the default behavior be? Should it be to send no body, null, or [] / {} when the body is nil or empty?

Yep You are right didn't read the docs well enough, my bad.(and im pretty new to go)
Thought it was a Huma thing as i couldn't think of it to be the "default" way.

It still Suprises me to be honest :P.

But yea not a Hma problem so closed

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

No branches or pull requests

3 participants