Go: JSON marshal empty arrays as "[]"

Created on 2 May 2019  路  3Comments  路  Source: golang/go

golang's stdlib encoding/json library currently marshals empty arrays as null rather than [], causing downstream JSON parsing to often fail.

Practically, many JSON parsers reject raw arrays that are not wrapped in some { blah: array } object structure. I think that is wasteful, but if encoding/json were to behave more predictably, it could have at least reported an error when Marshal() is passed an array instead of a struct / hashmap. Instead we get null for empty arrays, which is not a value anyone but old LISPers from the 50's would expect.

As a workaround, some Go users are substituting https://github.com/helloeave/json

Perhaps we can bring this improvement back to encoding/json, without breaking backwards compatibility, by introducing new methods and deprecating old methods.

All 3 comments

Dup of #27589.

Change https://golang.org/cl/205897 mentions this issue: encoding/json: Addnilasemptyoption

This issue only happens if array is primitive (e.g. string array). it worked fine for non-primitive array

Was this page helpful?
0 / 5 - 0 ratings