hn.today

A New Go API for JSON

go.dev387 points199 comments
Screenshot of A New Go API for JSON

Go 1.27 makes two new JSON packages generally available: encoding/json/v2, for translating between Go values and JSON, and encoding/json/jsontext, for working directly with JSON syntax. The change responds to long-standing problems in the original encoding/json package. Its defaults accept invalid UTF-8 and duplicate object names, marshal nil slices and maps as null, and match struct fields without regard to case. Some behaviors, such as inconsistent calls to pointer-receiver methods, are difficult to change without breaking existing programs. The older API also makes it hard to reject trailing input, pass options through custom methods, and avoid buffering and repeated parsing.

The new design separates syntax from meaning. jsontext provides streaming encoders and decoders for complete JSON values and individual tokens, with options available at construction. On top of it, v2 handles the relationship between JSON and Go types, while aiming to remain familiar enough that most v1 code can migrate with limited changes. New MarshalJSONTo and UnmarshalJSONFrom interfaces let custom types process data through streams, avoiding the extra allocation, validation, formatting, or parsing required by the older interfaces. The package split allows these improvements without changing v1’s compatibility guarantees; the stated goal is a safer, more flexible API with better performance.

Read on go.dev199 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.