Sunday, May 5, 2024
HomeJavaScriptWhy does JSON.parse corrupt massive numbers and the way to resolve this?

Why does JSON.parse corrupt massive numbers and the way to resolve this?


How can I forestall numbers from being corrupted by JSON.parse?

This concern of parsing massive numbers in JavaScript has been a recurring request from customers of https://jsoneditoronline.org/ through the years. Like most net based mostly JSON editors, it did additionally use the native JSON.parse perform and common JavaScript Numbers below the hood, so it suffered from the restrictions defined above.

A primary thought could also be: wait, however JSON.parse has an optionally available reviver argument, permitting you to parse content material differently. The issue although is that first the textual content is parsed right into a quantity, and subsequent, it’s handed to the reviver. So by then, it’s already too late and the quantity will likely be  corrupted already.

To resolve this concern, you merely can’t use the built-in JSON.parse and also you’ll have to make use of a distinct JSON parser as an alternative. There are numerous wonderful options for this accessible: lossless-json, json-bigint, js-json-bigint, or json-source-map. Most of those libraries take a realistic strategy, and parse lengthy numbers straight into the comparatively new BigInt JavaScript knowledge sort. The lossless-json library was developed specifically for JSON Editor On-line. It takes a extra versatile and highly effective strategy than the JSON BigInt options.

By default, lossless-json parses numbers into a light-weight LosslessNumber class, which holds the numeric worth as a string. This preserves any worth, and even preserves the formatting just like the trailing zero within the worth 4.0. When working on it, the LosslessNumber will likely be transformed into both a Quantity or BigInt, or an error will likely be thrown when it’s unsafe to take action. The library means that you can go your personal quantity parser, so you possibly can apply your personal technique to cope with numeric values. Perhaps you need to convert lengthy numeric values into BigInt, or go values into some BigNumber library. You may select whether or not you need to throw an exception when numeric info is misplaced, or silently ignore sure courses of knowledge loss.

So, evaluating the native JSON.parse perform and lossless-json, you get the next:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments