top | item 45187743

(no title)

tibbe | 5 months ago

> Since encoding/json marshals a nil slice or map as a JSON null

How did that make it into the v1 design?

discuss

order

rowanseymour|5 months ago

I had a back and forth with someone who really didn't want to change that behavior and their reasoning was that since you can create and provide an empty map or slice.. having the marshaler do that for you, and then also needing a way to disable that behavior, was unnecessary complexity.

stackedinserter|5 months ago

Why shouldn't it be? The nil is null and empty array is an empty array, they are completely different objects.

maleldil|5 months ago

Not in Go. Empty slices and empty maps are nil, so it's ambiguous.

binary132|5 months ago

how is a nil map not null? It certainly isn’t a zero-valued map, that would be {}.

materielle|5 months ago

It should be marshaled into {} by default, with a opt-out for special use cases.

There’s a simple reason: most JavaScript parsers reject null. At least in the slice case.

rplnt|5 months ago

Well those are different things, aren't they? Empty slice/map is different from nil. So it makes a lot of sense that nil = null and []string{} = [], and you have an option to use both. That being said, it starts to make less sense if you work with go where the API mostly treats it as equivalent (append, len, []). So that would be my guess how it ended up the way it did.

Also, now that nil map is an empty object, shouldn't that extend to every nil struct that doesn't have a custom marshaller? It would be an object if it wasn't nil after all...

int_19h|5 months ago

It is different from nil, but then again a nil map in Go behaves like an empty map when reading from it. If you consider serialization to be "reading", therefore, it makes sense to interpret it accordingly.