Requirements: I made an online parsing page for jwt, when the jwt content has a long type, using the default JSON method to parse will cause a loss of accuracy, as shown in the figure below:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiaXRzdnNlLmNvbSIsImlkIjo4OTA2MTM1NDg4MDEwNzc5Mjg1fQ.7tJHcSfbpZkgqw0ALGSRxyqkz2-UxZPhO_12TuKNZus
JavaScript has only one number type: Number, Number is a double-precision floating-point number, and unlike many other programming languages, JavaScript does not define different types of numbers, such as integers, short, long, floating-point, etc. Therefore, in JavaScript, numbers are not divided into integer types and floating-point types, and all numbers are floating-point types.
When expressing an integer, Number can represent an integer range of [−2 to the power of 53, 2 to the power of 253]. Because Number has 8 bytes and 64 bits, including 1 sign bit, 11 exponential bits, and 52 mantissa digits.
You can use Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER to view the maximum and minimum safety integers。
When the backend interface returns a field of type long, the frontend uses JSON.parse(text) to deserialize the display, which will cause a display error, and the solution is that the backend interface converts the field of type long to string type and returns it.
lossless-json project, parsing JSON without the risk of losing numeric information. GitHub address:The hyperlink login is visible.
First of allClone the lossless-json projectto build a bundled and minified library (ES5, PC needs to install node.js), and first install the dependencies:
Then compile as follows:
./dist/lossless-json.js This will generate an ES5 compatibility package that can be executed in the browser and node.js.
Tested via the browser console as follows:
Modify the project code,Introduce lossless-json.js files, calling LosslessJSON for JSON serialization and deserialization,Fixed the loss of accuracy issue, as shown in the figure below:
let json = LosslessJSON.parse('{"foo":"bar"}'); // {foo: 'bar'} let text = LosslessJSON.stringify(json); // '{"foo":"bar"}'
Test address:The hyperlink login is visible.
Finally, attach the compiled lossless-json.js file:
Tourists, if you want to see the hidden content of this post, please Reply (End) |