What steps can be taken to ensure that JSON.parse() interprets all numbers as BigInt values?

I'm dealing with numbers in JSON that exceed the limits of the Number type, so I'd like to convert them to bigint. How can I do this?

{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}

Answer №1

TLDR;

If you want to customize the behavior of `JSON.parse()`, you can utilize the `reviver` parameter.

Detailed Solution

To modify the behavior of `JSON.parse()`, you can use the `reviver` parameter, which is the second parameter of `JSON.parse`. This parameter is a function that preprocesses key-value pairs and can even convert values to `BigInt()`.

However, numbers are still coerced by default, as pointed out by @YohanesGultom. To preserve big numbers, you can wrap them in quotes in the source JSON string to convert them to `bigint`.

If you only want to convert certain numbers to `bigint`, you need to establish specific criteria, such as checking if the value exceeds `Number.MAX_SAFE_INTEGER` with `Number.isSafeInteger()`, recommended by @PeterSeliger.

One way to handle this problem is by implementing a function like this:

// Implementing desired criteria 
// for separating big numbers from small ones

const isBigNumber = num => !Number.isSafeInteger(+num)

// Wrapping big numbers in quotes inside
// the JSON string based on the criteria

const enquoteBigNumber = (jsonString, bigNumChecker) =>
    jsonString
        .replaceAll(
            /([:\s\[,]*)(\d+)([\s,\]]*)/g,
            (matchingSubstr, prefix, bigNum, suffix) =>
                bigNumChecker(bigNum)
                    ? `${prefix}"${bigNum}"${suffix}`
                    : matchingSubstr
        )

// Parsing the source JSON string 
// and converting matching big numbers to bigint

const parseWithBigInt = (jsonString, bigNumChecker) =>
    JSON.parse(
        enquoteBigNumber(jsonString, bigNumChecker),
        (key, value) =>
            !isNaN(value) && bigNumChecker(value)
                ? BigInt(value)
                : value
    )

// Output result

const output = parseWithBigInt(input, isBigNumber)

console.log("output.foo[1][0]: \n", output.foo[1][0], `(type: ${typeof output.foo[1][0]})`)
console.log("output.bar[0][0]: \n", output.bar[0][0].toString(), `(type: ${typeof output.bar[0][0]})`)
.as-console-wrapper{min-height: 100% !important;}

Note: If you find the RegExp pattern to match digit strings in JSON values lacking, feel free to create your own.

Note: While libraries are available, it's essential to consider the additional size they may add to your project, as mentioned by @YohanesGultom. Adding unnecessary bulk to your project for a single purpose may not be ideal.

Answer №2

If you're looking for a solution to handle large integers in JSON objects, my library might be just what you need. Check it out here: https://www.npmjs.com/package/json-with-bigint

Here's an example of how you can use it:

import { JSONParse } from 'json-with-bigint';
    
const yourJSON = `{"someValue":42,"someBigValue":10000000000000000365}`;

JSONParse(yourJSON); // { someValue: 42, someBigValue: 10000000000000000365n }

The library is smart enough to detect BigInt values automatically, so there's no need to specify which keys contain BigInt values.

Additionally, it provides consistent round-trip operations (parse - stringify - parse). This means that the values you deserialize will be identical to the ones you initially serialized, and vice versa.

import { JSONParse, JSONStringify } from 'json-with-bigint';
    
const yourJSON = `{"someValue":42,"someBigValue":10000000000000000365}`;

JSONParse(yourJSON); // { someValue: 42, someBigValue: 10000000000000000365n }
JSONStringify(data); // '{"someValue":42,"someBigValue":10000000000000000365}'
JSONParse(JSONStringify(data)); // { someValue: 42, someBigValue: 10000000000000000365n }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inverting the order of vertices in a THREE.js face

I am seeking a way to reverse the order of vertices in faces within my geometry. For instance: // create geometry var geometry = new THREE.Geometry(); // create vertices geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); geometry.vertices.push( ...

Converting a C++ string array to JSON: A step-by-step guide

Recently, I embarked on the journey of incorporating Microsoft Cognitive Services using C++. In my implementation, there exists a C++ String array named faceIds. string faceIds[] ={ "29e874a8-a08f-491f-84e8-eac263d51fe1", "6f89f38a ...

Tips for updating an object variable dynamically in an Angular application

const person = { "name": "jacob", "age": 22 } I am looking to dynamically update it to: { "name": "jacob", "age": 22, "dob": number } ...

Creating a tree-view in Vue.js that includes clickable components which trigger a Vue.js modal to open up

I have a unique requirement to implement a tree-view feature in Vue-JS for displaying JSON data. However, I need to enhance this by triggering a VueJS modal when any of the data fields in the JSON view are clicked. I have explored various npm modules that ...

Creating a dynamic dropdown menu based on a class value using JavaScript in PHP

There are two dropdown menus on my webpage that display information from my SQL table. The first dropdown contains different "Colors," and the second dropdown contains members associated with each color group. Each member is categorized into different optg ...

Upgrading the Spring framework from version 3.0.2 to 3.2.0 can lead to issues with Spring JSON functionality

While working on a web application using the Spring framework version 3.0.2 and Hibernate in NetBeans 6.9.1, I encountered a bug related to uploading multiple files as discussed in a previous question here. Despite my efforts, I couldn't find a soluti ...

Verify if a set of Radio buttons contains at least one option selected

Need help with validating a Feedback Form using either JQuery or Javascript. The requirement is to ensure that every group of radio-buttons has one option selected before the form can be submitted. Below is the code snippet from form.html: <form id=&ap ...

Developing an uncomplicated Angular promise following the invocation of a service

Delving into the realm of Angular promises for the first time, I'm determined to grasp its concepts. In my MainController, I have a simple authentication process using myAuthSrv.authUser with a username and password. Upon successful authentication (. ...

What are the steps for enlarging the display containing components with the 'position: absolute' style?

How can I magnify the screen with the following code? .drawing-board { width: 25%; height: 25%; background-color: black; position: relative; /* transform: scale(2, 2); */ } .drawing-board .box-1 { width: 20px; height: 20px; background-c ...

Guide to setting up npm openlpr in a Node.js environment

After attempting to install the npm node-openalpr package, I encountered an error. What steps can I take to resolve this issue? > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba5a4afaee6a4bbaea5aaa7bbb98bfae5fae5fa">[e ...

How come my form isn't functioning properly on mobile devices?

I recently downloaded a form from the website and integrated it within my desktop site successfully. However, when accessed on mobile devices, specifically iOS, the submit button changes to "sending ..." and the form gets stuck without displaying any erro ...

AngularJs stops the link from being clicked more than once

I am utilizing AngularJS for specific features in my system, not to build a single-page application. I am struggling to determine why Angular is preventing the page from refreshing after navigating there or how to disable/find a workaround. Here is an exa ...

Exploring the json simple library in Java to decode a jsonobject

{ "module": "xyz", "chapter": "2", "source": "Yahoo", "error": { "1": { "sourceLanguage": "Spanish", "message": "not available", "array": "[x, y, z]" }, "2": { "sourceLanguage": "Spanish", "message": "not ...

Retrieving the text content from a JSON key

I have the following JSON data saved in a jQuery variable called "jsondata": var jsondata = { "Name": { "Jaken": {}, "Test": {}, "Hello": {} }, "Date": { "Today": {}, "Tomorrow": {}, "Wednesday": {} }, "Description": { ...

Modifying a gridview cell through a Modal popup that is displayed using the rel attribute

I have successfully implemented a modal dialog using CSS and the rel="#showEditModal" attribute of a button. This enabled me to add values to the database and update the gridview effectively. However, I am now facing a challenge where I need to be able to ...

Obtaining the designated item within the list

My list contains elements obtained from a database. I want to ensure that the selected elements remain visible at all times, even after refreshing the page. Here's an example: <select id="select-firm" class="form-control" name="firmId" size="20" ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...

Quick method to send HTTPS JSON data (including headers and body) in Node.js

Feeling overwhelmed after sifting through various online posts discussing "JSON POST commands" in NodeJS. I attempted to create a simple script to communicate with a device's Restful API using https, but so far, I've hit a dead end... The JSON ...

Issues with React's onSelect event functionality are persisting

Is there an event handler in React for the onSelect statement? For example, when a user highlights some text within a paragraph using their mouse, is there a way to trigger an event that extracts the highlighted text? import React, { Component } from &apo ...

Exploring a React JS option for filtering repeated elements, as an alternative to Angular

While using Angular JS, I came across the 'filter' option within ng-repeat which is useful for live search. Here's an example: <div ng-repeat="std in stdData | filter:search"> <!-- Std Items go here. --> </div> &l ...