NPM Star
Collections
  1. Home
  2. Compare
  3. bson vs json5
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

Data Format Parsers: BSON vs JSON5

Both packages handle data formatting, but in different ways. BSON (Binary JSON) is MongoDB's binary format for storing documents, making data transfer more efficient but less readable. JSON5 is a more forgiving and human-friendly version of JSON that allows comments, trailing commas, and unquoted keys, making it easier for developers to write and maintain.

Data Parsing & Serializationdata-formatparsingserializationjsonmongodb

Detailed Comparison

Technical Analysis

featureComparison

BSON is a binary serialization format used to store and exchange data, while JSON5 is a superset of JSON that allows for more flexible syntax. BSON is more efficient in terms of storage and transmission, but JSON5 is more human-readable and easier to work with.

typescriptSupport

Both packages have TypeScript definitions, but BSON has more comprehensive type support.

browserCompatibility

Both packages are compatible with modern browsers, but BSON requires a polyfill for older browsers.

dependencies

BSON has no dependencies, while JSON5 depends on the `es5-ext` package.

performance

BSON is generally faster and more efficient than JSON5 due to its binary nature.

Ecosystem Analysis

frameworkCompatibility

Both packages are compatible with popular frameworks like React, Angular, and Vue.js.

communityActivity

BSON has a more active community and is widely used in MongoDB and other NoSQL databases.

documentationQuality

Both packages have good documentation, but BSON's documentation is more comprehensive and detailed.

maintenanceStatus

Both packages are actively maintained, but BSON has a more frequent release cycle.

Performance Comparison

bundleSizeAnalysis

JSON5 has a significantly smaller bundle size than BSON.

runtimePerformance

BSON is generally faster than JSON5 due to its binary nature.

loadingTime

JSON5 has a faster loading time than BSON due to its smaller bundle size.

memoryUsage

BSON uses more memory than JSON5 due to its binary storage.

Code Examples

BSON Example

1const BSON = require('bson');
2const doc = { _id: ObjectId, name: 'John', age: 30 };
3const bsonDoc = BSON.serialize(doc);

This example shows how to serialize a JavaScript object to BSON using the `bson` package.

JSON5 Example

1const json5 = require('json5');
2const data = { name: 'John', age: 30, comments: /* inline comment */ ['good', 'great'] };
3const jsonString = json5.stringify(data);

This example shows how to serialize a JavaScript object to JSON5 using the `json5` package, including inline comments.

Recommendation

Summary

Choose BSON for efficient data storage and transmission, and JSON5 for human-readable data exchange and flexible syntax.

Details

  • BSON is better suited for large-scale data storage and transmission due to its efficiency.
  • JSON5 is better suited for human-readable data exchange and debugging due to its flexibility.

Similar Packages

ejson

90%

Extended JSON library that supports special data types like Dates, Binary, and RegExp. It's like regular JSON but can handle more types of data that JSON normally can't.

Perfect alternative to BSON when you need to handle special data types but don't want the full MongoDB-specific features. It's lighter and easier to use for web applications.

Data Serialization

hjson

90%

Human JSON format that's more forgiving than regular JSON. Allows comments, missing quotes, and trailing commas to make config files easier to write.

Similar to JSON5 but with even more human-friendly features. Perfect for configuration files where you want to make it easy for humans to read and write.

JSON Parser

jsonc-parser

80%

A simple parser that supports JSON with comments, similar to JSON5. Used by VS Code and other popular tools for parsing configuration files.

Great alternative to JSON5 when you just need to handle comments in JSON files. It's faster and more focused than JSON5, though it has fewer features.

JSON Parser

msgpack

70%

Binary serialization format that's smaller and faster than JSON. Works like JSON but creates smaller files and processes them more quickly.

Good alternative to BSON when you need better performance and smaller file sizes. It's widely used in real-time applications and games.

Data Serialization

cbor

60%

Compact binary format that's similar to JSON but more efficient. It's like a smaller, faster version of JSON that works great for sending data between computers.

Good alternative to BSON when you need efficient binary encoding but don't need MongoDB-specific features. It's an internet standard and works well for IoT devices.

Data Serialization

BSON parser

BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in the specification.

Table of Contents

  • Usage
  • Bugs/Feature Requests
  • Installation
  • Documentation
  • FAQ

Release Integrity

Releases are created automatically and signed using the Node team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:

gpg --import node-driver.asc

The GitHub release contains a detached signature file for the NPM package (named bson-X.Y.Z.tgz.sig).

The following command returns the link npm package.

npm view bson@vX.Y.Z dist.tarball

Using the result of the above command, a curl command can return the official npm package for the release.

To verify the integrity of the downloaded package, run the following command:

gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz

[!Note] No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.

Bugs / Feature Requests

Think you've found a bug? Want to see a new feature in bson? Please open a case in our issue management tool, JIRA:

  1. Create an account and login: jira.mongodb.org
  2. Navigate to the NODE project: jira.mongodb.org/browse/NODE
  3. Click Create Issue - Please provide as much information as possible about the issue and how to reproduce it.

Bug reports in JIRA for the NODE driver project are public.

Usage

To build a new version perform the following operations:

npm install
npm run build

Node.js or Bundling Usage

When using a bundler or Node.js you can import bson using the package name:

import { BSON, EJSON, ObjectId } from 'bson'; // or: // const { BSON, EJSON, ObjectId } = require('bson'); const bytes = BSON.serialize({ _id: new ObjectId() }); console.log(bytes); const doc = BSON.deserialize(bytes); console.log(EJSON.stringify(doc)); // {"_id":{"$oid":"..."}}

Browser Usage

If you are working directly in the browser without a bundler please use the .mjs bundle like so:

<script type="module"> import { BSON, EJSON, ObjectId } from './lib/bson.mjs'; const bytes = BSON.serialize({ _id: new ObjectId() }); console.log(bytes); const doc = BSON.deserialize(bytes); console.log(EJSON.stringify(doc)); // {"_id":{"$oid":"..."}} </script>

Installation

npm install bson

MongoDB Node.js Driver Version Compatibility

Only the following version combinations with the MongoDB Node.js Driver are considered stable.

| | bson@1.x | bson@4.x | bson@5.x | bson@6.x | | ------------- | ---------- | ---------- | ---------- | ---------- | | mongodb@6.x | N/A | N/A | N/A | ✓ | | mongodb@5.x | N/A | N/A | ✓ | N/A | | mongodb@4.x | N/A | ✓ | N/A | N/A | | mongodb@3.x | ✓ | N/A | N/A | N/A |

Documentation

BSON

API documentation

<a name="EJSON"></a>

EJSON

  • EJSON

    • .parse(text, [options])

    • .stringify(value, [replacer], [space], [options])

    • .serialize(bson, [options])

    • .deserialize(ejson, [options])

<a name="EJSON.parse"></a>

EJSON.parse(text, [options])

| Param | Type | Default | Description | | ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- | | text | <code>string</code> | | | | [options] | <code>object</code> | | Optional settings | | [options.relaxed] | <code>boolean</code> | <code>true</code> | Attempt to return native JS types where possible, rather than BSON types (if true) |

Parse an Extended JSON string, constructing the JavaScript value or object described by that string.

Example

const { EJSON } = require('bson'); const text = '{ "int32": { "$numberInt": "10" } }'; // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } } console.log(EJSON.parse(text, { relaxed: false })); // prints { int32: 10 } console.log(EJSON.parse(text));

<a name="EJSON.stringify"></a>

EJSON.stringify(value, [replacer], [space], [options])

| Param | Type | Default | Description | | ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | value | <code>object</code> | | The value to convert to extended JSON | | [replacer] | <code>function</code> | <code>array</code> | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | | [space] | <code>string</code> | <code>number</code> | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | | [options] | <code>object</code> | | Optional settings | | [options.relaxed] | <code>boolean</code> | <code>true</code> | Enabled Extended JSON's relaxed mode | | [options.legacy] | <code>boolean</code> | <code>true</code> | Output in Extended JSON v1 |

Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Example

const { EJSON } = require('bson'); const Int32 = require('mongodb').Int32; const doc = { int32: new Int32(10) }; // prints '{"int32":{"$numberInt":"10"}}' console.log(EJSON.stringify(doc, { relaxed: false })); // prints '{"int32":10}' console.log(EJSON.stringify(doc));

<a name="EJSON.serialize"></a>

EJSON.serialize(bson, [options])

| Param | Type | Description | | --------- | ------------------- | ---------------------------------------------------- | | bson | <code>object</code> | The object to serialize | | [options] | <code>object</code> | Optional settings passed to the stringify function |

Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.

<a name="EJSON.deserialize"></a>

EJSON.deserialize(ejson, [options])

| Param | Type | Description | | --------- | ------------------- | -------------------------------------------- | | ejson | <code>object</code> | The Extended JSON object to deserialize | | [options] | <code>object</code> | Optional settings passed to the parse method |

Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types

Error Handling

It is our recommendation to use BSONError.isBSONError() checks on errors and to avoid relying on parsing error.message and error.name strings in your code. We guarantee BSONError.isBSONError() checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.

Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. This means BSONError.isBSONError() will always be able to accurately capture the errors that our BSON library throws.

Hypothetical example: A collection in our Db has an issue with UTF-8 data:

let documentCount = 0; const cursor = collection.find({}, { utf8Validation: true }); try { for await (const doc of cursor) documentCount += 1; } catch (error) { if (BSONError.isBSONError(error)) { console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`); return documentCount; } throw error; }

React Native

BSON vendors the required polyfills for TextEncoder, TextDecoder, atob, btoa imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, crypto.getRandomValues is recommended and can be installed with the following command:

npm install --save react-native-get-random-values

The following snippet should be placed at the top of the entrypoint (by default this is the root index.js file) for React Native projects using the BSON library. These lines must be placed for any code that imports BSON.

// Required Polyfills For ReactNative import 'react-native-get-random-values';

Finally, import the BSON library like so:

import { BSON, EJSON } from 'bson';

This will cause React Native to import the node_modules/bson/lib/bson.rn.cjs bundle (see the "react-native" setting we have in the "exports" section of our package.json.)

Technical Note about React Native module import

The "exports" definition in our package.json will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in React Native's runtime hermes.

FAQ

Why does undefined get converted to null?

The undefined BSON type has been deprecated for many years, so this library has dropped support for it. Use the ignoreUndefined option (for example, from the driver ) to instead remove undefined keys.

How do I add custom serialization logic?

This library looks for toBSON() functions on every path, and calls the toBSON() function to get the value to serialize.

const BSON = require('bson'); class CustomSerialize { toBSON() { return 42; } } const obj = { answer: new CustomSerialize() }; // "{ answer: 42 }" console.log(BSON.deserialize(BSON.serialize(obj)));

JSON5 – JSON for Humans

Build Status Coverage
Status

JSON5 is an extension to the popular JSON file format that aims to be easier to write and maintain by hand (e.g. for config files). It is not intended to be used for machine-to-machine communication. (Keep using JSON or other file formats for that. 🙂)

JSON5 was started in 2012, and as of 2022, now gets >65M downloads/week, ranks in the top 0.1% of the most depended-upon packages on npm, and has been adopted by major projects like Chromium, Next.js, Babel, Retool, WebStorm, and more. It's also natively supported on Apple platforms like MacOS and iOS.

Formally, the JSON5 Data Interchange Format is a superset of JSON (so valid JSON files will always be valid JSON5 files) that expands its syntax to include some productions from ECMAScript 5.1 (ES5). It's also a strict subset of ES5, so valid JSON5 files will always be valid ES5.

This JavaScript library is a reference implementation for JSON5 parsing and serialization, and is directly used in many of the popular projects mentioned above (where e.g. extreme performance isn't necessary), but others have created many other libraries across many other platforms.

Summary of Features

The following ECMAScript 5.1 features, which are not supported in JSON, have been extended to JSON5.

Objects

  • Object keys may be an ECMAScript 5.1 IdentifierName.
  • Objects may have a single trailing comma.

Arrays

  • Arrays may have a single trailing comma.

Strings

  • Strings may be single quoted.
  • Strings may span multiple lines by escaping new line characters.
  • Strings may include character escapes.

Numbers

  • Numbers may be hexadecimal.
  • Numbers may have a leading or trailing decimal point.
  • Numbers may be IEEE 754 positive infinity, negative infinity, and NaN.
  • Numbers may begin with an explicit plus sign.

Comments

  • Single and multi-line comments are allowed.

White Space

  • Additional white space characters are allowed.

Example

Kitchen-sink example:

{ // comments unquoted: 'and you can quote me on that', singleQuotes: 'I can use "double quotes" here', lineBreaks: "Look, Mom! \ No \\n's!", hexadecimal: 0xdecaf, leadingDecimalPoint: .8675309, andTrailing: 8675309., positiveSign: +1, trailingComma: 'in objects', andIn: ['arrays',], "backwardsCompatible": "with JSON", }

A more real-world example is this config file from the Chromium/Blink project.

Specification

For a detailed explanation of the JSON5 format, please read the official specification.

Installation and Usage

Node.js

npm install json5

CommonJS

const JSON5 = require('json5')

Modules

import JSON5 from 'json5'

Browsers

UMD

<!-- This will create a global `JSON5` variable. --> <script src="https://unpkg.com/json5@2/dist/index.min.js"></script>

Modules

<script type="module"> import JSON5 from 'https://unpkg.com/json5@2/dist/index.min.mjs' </script>

API

The JSON5 API is compatible with the JSON API.

JSON5.parse()

Parses a JSON5 string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Syntax

JSON5.parse(text[, reviver])

Parameters

  • text: The string to parse as JSON5.
  • reviver: If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Return value

The object corresponding to the given JSON5 text.

JSON5.stringify()

Converts a JavaScript value to a JSON5 string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON5.stringify(value[, replacer[, space]])
JSON5.stringify(value[, options])

Parameters

  • value: The value to convert to a JSON5 string.
  • replacer: A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON5 string. If this value is null or not provided, all properties of the object are included in the resulting JSON5 string.
  • space: A String or Number object that's used to insert white space into the output JSON5 string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used. If white space is used, trailing commas will be used in objects and arrays.
  • options: An object with the following properties:
    • replacer: Same as the replacer parameter.
    • space: Same as the space parameter.
    • quote: A String representing the quote character to use when serializing strings.

Return value

A JSON5 string representing the value.

Node.js require() JSON5 files

When using Node.js, you can require() JSON5 files by adding the following statement.

require('json5/lib/register')

Then you can load a JSON5 file with a Node.js require() statement. For example:

const config = require('./config.json5')

CLI

Since JSON is more widely used than JSON5, this package includes a CLI for converting JSON5 to JSON and for validating the syntax of JSON5 documents.

Installation

npm install --global json5

Usage

json5 [options] <file>

If <file> is not provided, then STDIN is used.

Options:

  • -s, --space: The number of spaces to indent or t for tabs
  • -o, --out-file [file]: Output to the specified file, otherwise STDOUT
  • -v, --validate: Validate JSON5 but do not output JSON
  • -V, --version: Output the version number
  • -h, --help: Output usage information

Contributing

Development

git clone https://github.com/json5/json5 cd json5 npm install

When contributing code, please write relevant tests and run npm test and npm run lint before submitting pull requests. Please use an editor that supports EditorConfig.

Issues

To report bugs or request features regarding the JSON5 data format, please submit an issue to the official specification repository.

Note that we will never add any features that make JSON5 incompatible with ES5; that compatibility is a fundamental premise of JSON5.

To report bugs or request features regarding this JavaScript implementation of JSON5, please submit an issue to this repository.

Security Vulnerabilities and Disclosures

To report a security vulnerability, please follow the follow the guidelines described in our security policy.

License

MIT. See LICENSE.md for details.

Credits

Aseem Kishore founded this project. He wrote a blog post about the journey and lessons learned 10 years in.

Michael Bolin independently arrived at and published some of these same ideas with awesome explanations and detail. Recommended reading: Suggested Improvements to JSON

Douglas Crockford of course designed and built JSON, but his state machine diagrams on the JSON website, as cheesy as it may sound, gave us motivation and confidence that building a new parser to implement these ideas was within reach! The original implementation of JSON5 was also modeled directly off of Doug’s open-source json_parse.js parser. We’re grateful for that clean and well-documented code.

Max Nanasy has been an early and prolific supporter, contributing multiple patches and ideas.

Andrew Eisenberg contributed the original stringify method.

Jordan Tucker has aligned JSON5 more closely with ES5, wrote the official JSON5 specification, completely rewrote the codebase from the ground up, and is actively maintaining this project.

StarsIssuesVersionUpdatedⓘLast publish dateCreatedⓘPackage creation dateSizeⓘMinified + Gzipped size
B
bson
1,18586.10.4a month ago14 years agoinstall size 20.8 KB
J
json5
6,899362.2.32 years ago13 years agoinstall size 9.3 KB

Dependencies Comparison

bson

Dependencies

Dev Dependencies

@istanbuljs/nyc-config-typescript^1.0.2
@microsoft/api-extractor^7.52.5
@rollup/plugin-node-resolve^16.0.1
@rollup/plugin-typescript^12.1.2
@types/chai^4.3.17
@types/mocha^10.0.7
@types/node^22.15.3
@types/sinon^17.0.4
@types/sinon-chai^3.2.12
@typescript-eslint/eslint-plugin^8.31.1
@typescript-eslint/parser^8.31.1
benchmark^2.1.4
chai^4.4.1
chalk^5.3.0
dbx-js-toolsgithub:mongodb-js/dbx-js-tools#main
eslint^9.25.1
eslint-config-prettier^10.1.2
eslint-plugin-no-bigint-usagefile:etc/eslint/no-bigint-usage
eslint-plugin-prettier^5.2.6
eslint-plugin-tsdoc^0.4.0
magic-string^0.30.11
mocha^10.7.0
node-fetch^3.3.2
nyc^15.1.0
prettier^3.5.3
rollup^4.40.1
sinon^18.0.0
sinon-chai^3.7.0
source-map-support^0.5.21
tar^7.4.3
ts-node^10.9.2
tsd^0.31.1
typescript^5.8.3
typescript-cached-transpile0.0.6
uuid^11.1.0

Peer Dependencies

json5

Dependencies

Dev Dependencies

core-js^2.6.5
eslint^5.15.3
eslint-config-standard^12.0.0
eslint-plugin-import^2.16.0
eslint-plugin-node^8.0.1
eslint-plugin-promise^4.0.1
eslint-plugin-standard^4.0.0
npm-run-all^4.1.5
regenerate^1.4.0
rollup^0.64.1
rollup-plugin-buble^0.19.6
rollup-plugin-commonjs^9.2.1
rollup-plugin-node-resolve^3.4.0
rollup-plugin-terser^1.0.1
sinon^6.3.5
tap^12.6.0
unicode-10.0.0^0.7.5

Peer Dependencies

Who's Using These Packages

bson

json5

zhihuhelp
zhihuhelp

基于node&typescript重写知乎助手

sonarqube-webapp
sonarqube-webapp

SonarQube Community Build Web App