Languages

JavaScript - Uncaught TypeError: Do not know how to serialize a BigInt

7 points
Asked by:
Zayaan-Rasmussen
543

Any idea, why JSON.stringify() throws:

Uncaught TypeError: Do not know how to serialize a BigInt

when I try to use:

// ONLINE-RUNNER:browser;

const object = {
    key: 'code',
    value: 123n
};

const json = JSON.stringify(object);

console.log(json);
1 answer
5 points
Answered by:
Zayaan-Rasmussen
543

JSON.stringify() doesn't support BitInt type.

You can solve the problem by:

  1. own non-standard JSON.stringify() implementaion,
  2. sending Number or String type instead of BigInt type,
  3. using some wrapping source code.

Solution 1

That approach is too complicated and breaks JSON standard rules, so I will focus on other solutions.

 

Solution 2

As example we can use String type to store BigInt type, knowing the value can be very big.

The main disadvantage of this solution is necessity to keep information about what properties have BigInt type.

Quick solutions

e.g. 1:

BigInt.prototype.toJSON = function() { return this.toString() };

e.g. 2:

const json = JSON.stringify(object , (key, value) => {
    return typeof value === 'bigint' ? value.toString() : value;
});

Practical examples

e.g. 1:

// ONLINE-RUNNER:browser;

BigInt.prototype.toJSON = function() {  // <------------
    return this.toString();             // <--- SOLUTION
};                                      // <------------

const inputObject = {
    key: 'code',
    value: 123n
};

const customJson = JSON.stringify(inputObject);
const outputObject = JSON.parse(customJson);

console.log(`JSON: ${customJson}\n\n`);
console.log(`TYPE: ${typeof outputObject.key}  VALUE: ${outputObject.key}`);
console.log(`TYPE: ${typeof outputObject.value}  VALUE: ${outputObject.value}`);

e.g. 2:

// ONLINE-RUNNER:browser;

const inputObject = {
    key: 'code',
    value: 123n
};

const customJson = JSON.stringify(inputObject , (key, value) => {  // <------------
    return typeof value === 'bigint' ? value.toString() : value;   // <--- SOLUTION
});                                                                // <------------

const outputObject = JSON.parse(customJson);

console.log(`JSON: ${customJson}\n\n`);
console.log(`TYPE: ${typeof outputObject.key}  VALUE: ${outputObject.key}`);
console.log(`TYPE: ${typeof outputObject.value}  VALUE: ${outputObject.value}`);  // we need to do conversion to BigInt manually, e.g. BigInt(outputObject.value)

 

Solution 3

As example we can use for BigInt type objects some wrapping object.

e.g.

// ONLINE-RUNNER:browser;

const renderJson = (object) => {
    return JSON.stringify(object, (key, value) => {
        switch (typeof value) {
            case 'bigint':
                return {  // warpper
                    $T$: 'bigint',         // type   // maybe it is good to use some more complicated name instead of $T$
                    $V$: value.toString()  // value  // maybe it is good to use some more complicated name instead of $V$
                };
            // Put more cases here ...
            default:
                return value;
        }
    });
};

const pareseJson = (json) => {
    return JSON.parse(json, (key, value) => {
        if (typeof value === 'object') {
            switch (value?.$T$) {
                case 'bigint':  // warpper
                    return BigInt(value.$V$);
                // Put more cases here ...
                default:
                    return value;
            }
        } else {
            return value;
        }
    });
};


// Usage example:

const inputObject = {
    key: 'code',
    value: 123n
};

const customJson = renderJson(inputObject);
const outputObject = pareseJson(customJson);

console.log(`JSON: ${customJson}\n\n`);
console.log(`TYPE: ${typeof outputObject.key}  VALUE: ${outputObject.key}`);
console.log(`TYPE: ${typeof outputObject.value}  VALUE: ${outputObject.value}`);

 

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join