@apimatic/json-bigint

中文文档
1.2.0发布于 2022/03/14MITTypeScriptCommonJS零依赖近 30 天下载 144.6万

JSON.parse with bigints support

原始使用文档
文档目录3 节
  1. Options
  2. Links:
  3. Note on native BigInt support

@apimatic/json-bigint

Build Status

JSON.parse/stringify with bigints support. Based on Douglas Crockford JSON.js package. This is a fork of json-bigint. This module does not have the support for bignumber.js and thus has that dependeny removed.

Install the library using npm:

$ npm install @apimatic/json-bigint

While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification does not say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but { "value" : 9223372036854775807}, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of JSON.parse is this object: { value: 9223372036854776000 }

==========

example:

var JSONbig = require('@apimatic/json-bigint');

var json = '{ "value" : 9223372036854775807, "v2": 123 }';
console.log('Input:', json);
console.log('');

console.log('node.js built-in JSON:');
var r = JSON.parse(json);
console.log('JSON.parse(input).value : ', r.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));

console.log('\n\nbigint JSON:');
var r1 = JSONbig.parse(json);
console.log('JSONbig.parse(input).value : ', r1.value.toString());
console.log('JSONbig.stringify(JSONbig.parse(input)):', JSONbig.stringify(r1));

Output:

Input: { "value" : 9223372036854775807, "v2": 123 }

node.js built-in JSON:
JSON.parse(input).value :  9223372036854776000
JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123}


bigint JSON:
JSONbig.parse(input).value :  9223372036854775807
JSONbig.stringify(JSONbig.parse(input)): {"value":9223372036854775807,"v2":123}

Options

The behaviour of the parser is somewhat configurable through 'options'

options.strict, boolean, default false

Specifies the parsing should be "strict" towards reporting duplicate-keys in the parsed string. The default follows what is allowed in standard json and resembles the behavior of JSON.parse, but overwrites any previous values with the last one assigned to the duplicate-key.

Setting options.strict = true will fail-fast on such duplicate-key occurances and thus warn you upfront of possible lost information.

example:

var JSONbig = require('@apimatic/json-bigint');
var JSONstrict = require('@apimatic/json-bigint')({ strict: true });

var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}';
console.log('\n\nDuplicate Key test with both lenient and strict JSON parsing');
console.log('Input:', dupkeys);
var works = JSONbig.parse(dupkeys);
console.log('JSON.parse(dupkeys).dupkey: %s', works.dupkey);
var fails = 'will stay like this';
try {
  fails = JSONstrict.parse(dupkeys);
  console.log('ERROR!! Should never get here');
} catch (e) {
  console.log(
    'Succesfully catched expected exception on duplicate keys: %j',
    e
  );
}

Output

Duplicate Key test with big number JSON
Input: { "dupkey": "value 1", "dupkey": "value 2"}
JSON.parse(dupkeys).dupkey: value 2
Succesfully catched expected exception on duplicate keys: {"name":"SyntaxError","message":"Duplicate key \"dupkey\"","at":33,"text":"{ \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}"}

options.storeAsString, boolean, default false

Specifies if BigInts should be stored in the object as a string.

Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all BigInts to be-and-stay strings).

example:

var JSONbig = require('@apimatic/json-bigintt');
var JSONbigString = require('@apimatic/json-bigint')({ storeAsString: true });
var key = '{ "key": 1234567890123456789 }';
console.log('\n\nStoring the BigInt as a string, instead of a BigInt');
console.log('Input:', key);
var withInt = JSONbig.parse(key);
var withString = JSONbigString.parse(key);
console.log(
  'Default type: %s, With option type: %s',
  typeof withInt.key,
  typeof withString.key
);

Output

Storing the BigInt as a string, instead of a BigInt
Input: { "key": 1234567890123456789 }
Default type: bigint, With option type: string

options.alwaysParseAsBig, boolean, default false

Specifies if all numbers should be stored as BigInt.

Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all Number to be-and-stay BigInt)

example:

var JSONbig = require('@apimatic/json-bigint');
var JSONbigAlways = require('@apimatic/json-bigint')({ alwaysParseAsBig: true });
var key = '{ "key": 123 }'; // there is no need for BigInt by default, but we're forcing it
console.log(`\n\nStoring the Number as a BigInt, instead of a Number`);
console.log('Input:', key);
var normal = JSONbig.parse(key);
var always = JSONbigAlways.parse(key);
console.log(
  'Default type: %s, With option type: %s',
  typeof normal.key,
  typeof always.key
);

Output

Storing the Number as a BigInt, instead of a Number
Input: { "key": 123 }
Default type: number, With option type: bigint

options.protoAction, boolean, default: "error". Possible values: "error", "ignore", "preserve"

options.constructorAction, boolean, default: "error". Possible values: "error", "ignore", "preserve"

Controls how __proto__ and constructor properties are treated. If set to "error" they are not allowed and parse() call will throw an error. If set to "ignore" the prroperty and it;s value is skipped from parsing and object building. If set to "preserve" the __proto__ property is set. One should be extra careful and make sure any other library consuming generated data is not vulnerable to prototype poisoning attacks.

example:

var JSONbigAlways = require('@apimatic/json-bigint')({ protoAction: 'ignore' });
const user = JSONbig.parse('{ "__proto__": { "admin": true }, "id": 12345 }');
// => result is { id: 12345 }

Note on native BigInt support

Stringifying

Full support out-of-the-box, stringifies BigInts as pure numbers (no quotes, no n)

Limitations

  • Roundtrip operations

s === JSONbig.stringify(JSONbig.parse(s)) but

o !== JSONbig.parse(JSONbig.stringify(o))

when o has a value with something like 123n.

JSONbig stringify 123n as 123, which becomes number (aka 123 not 123n) by default when being reparsed.

There is currently no consistent way to deal with this issue, so we decided to leave it, handling this specific case is then up to users.

版本与发布记录

@apimatic/json-bigint 共发布 7 个版本,首次发布于 2021/09/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.0latest2022/03/144 年前
1.1.02021/09/285 年前
1.1.0-alpha.12021/09/285 年前
1.1.0-alpha.02021/09/285 年前
1.0.12021/09/085 年前
1.0.02021/09/085 年前

关于 @apimatic/json-bigint 的常见问题

@apimatic/json-bigint 是什么?

JSON.parse with bigints support

如何安装 @apimatic/json-bigint?

在项目目录运行 npm install @apimatic/json-bigint,或使用 pnpm add / yarn add / bun add。

@apimatic/json-bigint 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@apimatic/json-bigint 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@apimatic/json-bigint 可以商用吗?

@apimatic/json-bigint 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@apimatic/json-bigint 的下载量有多少?

根据 npm 官方下载统计,@apimatic/json-bigint 在 2026/10/06 – 2026/11/04 这 30 天内被下载 1,446,138 次,日均约 48,205 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@apimatic/json-bigint 还在维护吗?

最新版本 1.2.0 发布于 2022/03/14(4 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/09/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。