0.1.0 • Published 2 years ago

json-bn v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Build Status npm NPM npm

json-bn is a library to solve the problem of big number double precision loss when parsing JSON string. It can also convert big numbers to the type you want according to your configuration, such as bigint, string, etc.

While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification does not say anything about number precision.

ESM:

node >= 13.2.0 // Because node supports EMS import after version 13.2.0 

CJS:

node >= 0

example 1:

const { parse } = require('json-bn');

const jsonStr = '{"bn":18014398509481981,"small":123,"deci":1234567890.0123456}';

console.log('Input:', jsonStr);

console.log('origin JSON.parse:');
const origin = JSON.parse(jsonStr);
console.log('JSON.parse(jsonStr).bn : ', origin.bn.toString());


console.log('\n\nuse json-bn parse:');
const jsonBn = parse(jsonStr);
console.log('parse(jsonStr).bn : ', jsonBn.bn.toString());

Output:

Input: {"bn":18014398509481981,"small":123,"deci":1234567890.0123456}
origin JSON.parse:
JSON.parse(jsonStr).bn :  18014398509481980


use json-bn parse:
parse(jsonStr).bn :  18014398509481981

example 2:

const { parse } = require('json-bn');

const jsonStr = '{"bn":18014398509481981,"small":123,"deci":1234567890.0123456}';

console.log('Input:', jsonStr);

console.log('\nuse json-bn parse:');
const jsonBn = parse(jsonStr, {
    useType: 'bigint', // Three types are support: 'string', 'bigint', 'array';
});
console.log('parse(jsonStr).bn : ', jsonBn.bn);
console.log('parse(jsonStr).bn.toString() : ', jsonBn.bn.toString());

output:

Input: {"bn":18014398509481981,"small":123,"deci":1234567890.0123456}

use json-bn parse:
parse(jsonStr).bn :  18014398509481981n
parse(jsonStr).bn.toString() :  18014398509481981

example 3: ESM is supported, but the node version must be above 13.2.0

import { parse } from 'json-bn';

const jsonStr = '{"bn":18014398509481981,"small":123,"deci":1234567890.0123456}';

console.log('Running node version: ', process.version);
console.log('Input:', jsonStr);

console.log('\nuse json-bn parse:');
const jsonBn = parse(jsonStr, {
    useType: 'string', // Three types are support: 'string', 'bigint', 'array';
});
console.log('parse(jsonStr).bn : ', jsonBn.bn);

output:

Running node version:  v14.18.3
Input: {"bn":18014398509481981,"small":123,"deci":1234567890.0123456}

use json-bn parse:
parse(jsonStr).bn :  18014398509481981
0.1.0

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago