npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@haixing_hu/json

v1.0.3

Published

A JavaScript library for parsing and formatting JSON data.

Downloads

292

Readme

Enhanced JSON Parsing and Stringification for Large Numbers and Collections

npm package License CircleCI Coverage Status

@haixing_hu/json is a JavaScript library that extends the functionality of the standard JSON object, providing robust support for working with numbers that exceed JavaScript’s safe range. It offers enhanced parsing and stringifying capabilities, making it ideal for handling large datasets and complex numerical operations while adhering to JSON’s structure.

Key Features

  • BigInt Support: When parsing JSON strings, numbers outside JavaScript’s safe integer range are automatically converted to the native BigInt, ensuring precision is maintained.
  • LosslessNumber Handling: For floating-point numbers that cannot be accurately represented in JavaScript, this library introduces the LosslessNumber object. This lightweight object preserves the full precision of the number as a string, allowing flexible conversion to number or BigInt for mathematical operations.
  • Accurate Stringification: During the stringify process, BigInt values are serialized as strings without the “n” suffix, maintaining compatibility with the standard JSON format. Similarly, LosslessNumber objects are serialized using their internal string representation.
  • Collection Serialization: JavaScript’s native collections like Set and Map are seamlessly serialized as arrays, allowing for better compatibility with JSON structures.

For more details on why JSON parsing can corrupt large numbers and how this library helps resolve the issue, refer to Why does JSON.parse corrupt large numbers and how to solve this?.

Installation

To install the library, use either npm or yarn:

npm install @haixing_hu/json

or

yarn add @haixing_hu/json

Core Functionality

JSON-like Object

The library provides an object similar to the standard JSON object, but with enhanced capabilities for handling large integers, floating-point numbers, and collections like Set and Map.

import Json from '@haixing_hu/json';

// parse numbers outside the safe range
const str1 = '{"decimal":2.370,"big_int":9123372036854000123,"big_float":2.3e+500}';
const obj1 = Json.parse(text);
console.log(obj1.decimal);   // 2.37
console.log(obj1.big_int);   // 9123372036854000123n
console.log(obj1.big_float); // LosslessNumber { value: '2.3e+500', isLosslessNumber: true }
console.log(String(obj1.big_float)); // '2.3e+500'

// stringify numbers outside the safe range
const json1 = Json.stringify(obj1);
console.log(json1); // '{"decimal":2.37,"big_int":9123372036854000123,"big_float":"2.3e+500"}'

// stringify collections
const obj2 = { 
  x: new Set([{ a: 1 }, { b: 2 }, { c: 3 }]),
  y: new Map([[1, { a: 2 }], [2, { b: 4 }]]),
};
const json2 = Json.stringify(obj);
console.log(json2); // '{"x":[{"a":1},{"b":2},{"c":3}],"y":[[1,{"a":2}],[2,{"b":4}]]}'

const json3 = Json.stringify(obj, null, 2);
console.log(json3); // 

LosslessNumber Class

The LosslessNumber class is used to handle floating-point numbers with full precision, avoiding truncation or rounding issues.

import Json from '@haixing_hu/json';
const parsed = Json.parse('{"float": 1.234567891234567891234}');
console.log(parsed.float);  // LosslessNumber { value: '1.234567891234567891234' }

// Convert LosslessNumber to standard number
console.log(parsed.float.valueOf());  // 1.2345678912345679 (standard JS number)

Utility Functions

This library provides a set of utility functions to aid in the handling of large numbers and ensure safe conversions.

isBigInt(value)

Checks if a string represents a BigInt (i.e., ends with an “n” suffix).

import { isBigInt } from '@haixing_hu/json';

console.log(isBigInt('12345n'));  // true
console.log(isBigInt('12345'));   // false

isInteger(value)

Checks if a string represents an integer.

import { isInteger } from '@haixing_hu/json';

console.log(isInteger('12345'));  // true
console.log(isInteger('123.45')); // false

isNumber(value)

Checks if a string represents a number.

import { isNumber } from '@haixing_hu/json';

console.log(isNumber('12345'));     // true
console.log(isNumber('-123.45'));   // true
console.log(isNumber('1.23e-11'));  // true
console.log(isNumber('abc'));       // false

isSafeNumber(value, options)

Checks if a string represents a number within JavaScript’s safe range.

import { isSafeNumber } from '@haixing_hu/json';

console.log(isSafeNumber('12345'));     // true
console.log(isSafeNumber('12345678901234567890')); // false
console.log(isSafeNumber('123.45678901234567890')); // false
console.log(isSafeNumber('123.45678901234567890', { approx: true, requiredDigits: 16 })); // true

getUnsafeReason(value)

Explains why a number represented by a string is unsafe, returning one of the following reasons:

  • 'overflow'
  • 'underflow'
  • 'truncate_integer'
  • 'truncate_float'
  • 'none': when the value is safe
import { getUnsafeReason } from '@haixing_hu/json';

console.log(getUnsafeReason('12345'));     // Output: 'none'
console.log(getUnsafeReason('12345678901234567890')); // Output: 'truncate_integer'
console.log(getUnsafeReason('-12345678901234567890.123'));  //  Output: 'truncate_float'
console.log(getUnsafeReason('-1e+1000'));   // Output: 'overflow'
console.log(getUnsafeReason('1e-324'));     // Output: 'underflow'

toSafeNumberOrThrow(value, options)

Converts a string into a number if it is safe to do so. Throws an error if the number is unsafe, explaining the reason.

import { toSafeNumberOrThrow } from '@haixing_hu/json';

try {
  console.log(toSafeNumberOrThrow('-12345678901234567890'));
} catch (e) {
  console.error(e.message);  // Output: 'Cannot safely convert to number: the value '-12345678901234567890' would truncate integer and become -12345678901234567000'
}

console.log(toSafeNumberOrThrow('9007199254740991'));  // Output: 9007199254740991

Contributing

If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request to the GitHub repository.

License

@haixing_hu/json is distributed under the Apache 2.0 license. See the LICENSE file for more details.

Acknowledgements

This project builds upon and incorporates code from several open-source libraries that have made significant contributions to handling large numbers and custom parsing in JSON. We would like to acknowledge and thank the authors of the following projects:

  • json-bigint: Provides support for parsing and stringifying JSON with BigInt, allowing for precise handling of large numbers.
  • lossless-json: A library that offers lossless handling of numbers in JSON, ensuring full precision when dealing with floating-point values.
  • json-custom-numbers: Allows for custom handling of numbers in JSON parsing and stringifying, offering flexibility in numerical representation.

We are grateful for the work of these contributors, which has been instrumental in shaping the functionality of this library.