XUtils

json-strictify

Safely serialize a value to JSON without data loss or going into an infinite loop.


Typescript npm GitHub Workflow Status GitHub Issues libraries.io Codecov npm bundle size

json-strictify

Safely serialize a value to JSON without unintended loss of data or going into an infinite loop due to circular references.

Examples

The stringify function throws an error if the input to be serialized contains invalid values:

import JSONs from 'json-strictify'

JSONs.stringify({ x: 42, y: NaN })
// InvalidValueError: Invalid value at /y (NaN is not JSON-serializable)

Also, if the data you want to stringify contains circular references a CircularReferenceError is thrown:

const data = []
data.push(data)
JSONs.stringify(data)
// CircularReferenceError: Circular reference found at "/0"

The location of the value that caused the error is given as a JSON Pointer reference.


ESLint integration

If you want to ensure that all serialization is done through json-strictify you can disable the global JSON variable like so:

"globals": {
    "JSON": "off"
}

See the ESLint documentation on configuring globals for details.


Disabling json-strictify

In production you may not want to have the additional overhead introduced by json-strictify. This can easily be avoided by calling the enabled method:

import JSONs from 'json-strictify'
const JSON = JSONs.enabled(config.debug)

// or for older versions of Javascript:
const JSON = require('json-strictify').enabled(config.debug)

If called with a falsy parameter, enabled will return an object that delegates directly to the native JSON object so there will be no performance penalty whatsoever.

Note: json-strictify is disabled by default if NODE_ENV is set to production (you may still enable it manually, of course).


Articles

  • coming soon...