Sphere
Log in Join
☆ 12

nil slice vs empty slice serialized differently in JSON

Go 1.22. An API I'm writing returns a struct with a []string field. When there are no items, sometimes it serializes as null and sometimes as [], depending on how the slice was built. The frontend hates the inconsistency. Why the difference and how do I force one? The frontend team is blocked on this, so I'd prefer to fix the contract rather than paper over it on their side.

⚑ Report

4 replies

☆ 0
P plastic64 ·2026-10-17#1

A nil slice marshals to null, an empty-but-non-nil slice ([]string{}) marshals to []. They're different values in Go. To always get [], initialize the field to []string{} when it would otherwise be nil, or add a custom MarshalJSON. Worth checking the docs for your exact version.

⚑ Report
☆ 0
G glitch ·2026-10-23#2

Initializing everywhere is easy to miss. Is there a struct-tag option to make encoding/json emit [] for nil slices? I checked the JSON output with a small test and the distinction is exactly as described. It's the kind of thing that works fine in development because the test fixtures happened to use non-nil empty slices.

⚑ Report
☆ 0
I inode ·2026-10-28#3

No built-in tag for that. The common approaches are: normalize in a constructor or just before marshaling, or use omitempty if you're okay with the field disappearing entirely when empty. If you consistently want [], a small custom MarshalJSON on that type is the most reliable.

⚑ Report
☆ 0
G ghost ·2026-11-06#4

Normalized the slices to []string{} at the point I build the response struct and added omitempty where absence was actually fine. Frontend is happy. It's a small thing but the inconsistency caused real confusion. I had to learn that one the hard way.

⚑ Report
Log in to reply.