Menu

JSON that parses without an error and still comes out different
📰

JSON that parses without an error and still comes out different

DEV Community: tutorial·Toolsy Hub·10 days ago
#lG9YMwXc
#devtotutorial#devto#dev#json#parse
Long article (339 words) — no AI summary yet.
Reading 0:00
15s threshold

A syntax error is the easy JSON bug: the parser tells you the line and column. The harder ones are documents that parse cleanly and hand you different data than the file held. Two come up often.

Big integers lose digits. JSON has no integer limit, but JSON.parse reads every number as a double, which is exact only up to 2^53 - 1.

console . log ( JSON . parse ( '{"id": 9007199254740993}' ) . id ) // 9007199254740992 console . log ( Number . MAX_SAFE_INTEGER ) // 9007199254740991

Enter fullscreen mode

Exit fullscreen mode

The id ends in 2 instead of 3, no error. Twitter-style snowflake ids and database bigints hit this. The fix on the wire is to send such ids as strings. If you cannot change the sender, current Node and browsers let a reviver see the original text:

JSON . parse ( '{"id":9007199254740993}' , ( k , v , ctx ) => ( typeof v === "number" ? ctx . source : v ) ) . id // '9007199254740993'

Enter fullscreen mode

Exit fullscreen mode

Duplicate keys keep the last value.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.