Jason Green
Jason’s passion for the digital world has taken him across the entire spectrum of the creative process, from conceptualization to deployment. Jason is now Director of Technology at Threads Styling, building a platform to empower personal shoppers and power the future of chat commerce.
Parse, Don’t Validate
Node Congress 2023Node Congress 2023
Parse, Don’t Validate
Most JavaScript applications use JSON.parse to create any object first, and then validate and narrow the data type to the expected one. This approach has performance and security problems, as even if the data is invalid, the whole JSON string needs to be parsed first before the data is validated, instead of failing at JSON parsing stage (e.g., if number is passed instead of string in some property).
Many languages support parsing of JSON strings directly into the expected types, but it is not natively supported in JavaScript or TypeScript.
In this talk we will show how the powers of TypeScript combined with the new specification JSON Type Definition (RFC 8927) and Ajv library can be used to parse your data directly into the expected application-defined type faster than JSON.parse, and also how to serialize data of a known type approximately 10 times faster than JSON.serialize.