Evgeny Poberezkin
Evgeny Poberezkin
SimpleX Chat (http://simplex.chat) founder - the 1st chat platform that does not have any user identifiers. Created Ajv JSON validator used by millions of JS apps.
Node Congress 2023Node Congress 2023
26 min
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.