points by SkiFire13 3 days ago | 0 comments
> nil slices and maps are marshaled as an empty JSON array or object by default
I feel that is the kind of broken default that will come back and bite a bunch of people, and will eventually need to be fixed in a v3.
[–] devmor 3 days ago
Can you explain why? This seems like the appropriate expectation to me, given how JSON is constructed and consumed.
[–] Someone 3 days ago
Not the OP, but serializing both nil and empty arrays to the same json string means round tripping will not work for all objects.
That seems like a bad default to me.
[–] throwaway894345 3 days ago
How is this a broken default? In Go, I almost always want a nil slice to be treated exactly as an empty slice, and JSONv1 was the ~only place this didn’t work as expected, leading to frequent bugs.
[–] c-hendricks 2 days ago
JSON often means data is crossing a boundary, and JSON has `null`. So if you have a PATCH endpoint that accepts a partial object, how do you determine what was actually set in the request vs what go has initialized to an empty value.
[–] throwaway894345 2 days ago
Use the same `Option[T]` type that you will need to define for strings and numbers and structs.
[–] c-hendricks 2 days ago
What was the solution before go had generics? I thought it was nil pointers.
[–] throwaway894345 2 days ago
I don’t think there was a single canonical solution, but pointers to everything was a pretty common one. Everything in the AWS SDK was a `string` or a `float64` or similar—it was exceedingly annoying, not least of all because it basically forced tons of unnecessary allocations.
[–] the_gipsy 3 days ago
The root cause is this idea of "zero values". Any de/serialization in go will always be crutchwork of guessing and incorrect validation.
Just look at the inane rules for map and slice access, what gets nil, what gets the zero value, which built-in mist be used. Even if that were consistent, then you'd still left to wonder if json.field was truly zero or not there.
[–] Vaushite 2 days ago
In Golang a nil value is semantically an empty container. You wouldn't want this translation in Java but in Golang it makes sense.
[–] travisd 3 days ago
[–] SkiFire13 3 days ago
This is definitely not what I expect in other language. I would argue this is a quick of Go though and not JSON's fault.