JavaScript Stringify

2.1.0 · active · verified Sun Apr 19

The `javascript-stringify` library provides a function, `stringify`, that converts JavaScript values into a string representation that can be safely `eval`'d back into JavaScript, in contrast to `JSON.stringify` which outputs JSON. It supports serializing a wider range of JavaScript types, including regular expressions, `Date` objects, `Number` objects, `Error`, `Map`, `Set`, and most notably, functions (including ES methods, async, and generator functions). It also handles circular references by default omitting them or, with an option, restoring them via an IIFE. The current stable version is 2.1.0. Releases appear driven by bug fixes and feature enhancements rather than a strict cadence, with significant changes like TypeScript rewrite and ESM transition occurring in major versions. Its primary differentiator is the ability to produce evaluable JavaScript code, making it useful for scenarios like code generation or transmitting configuration that includes functional logic.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `stringify` with various data types, including functions, dates, regex, and options like `references` for circular handling and `maxDepth`.

import { stringify } from 'javascript-stringify';

const exampleData = {
  id: 1,
  name: 'Complex Object',
  date: new Date('2023-01-15T10:00:00Z'),
  regex: /\btest\b/gi,
  status: null,
  computed: function(a, b) { return a + b; },
  nested: {
    value: 42,
    metadata: new Map([['key1', 'val1'], ['key2', 'val2']])
  }
};

// Add a circular reference to demonstrate handling
exampleData.selfRef = exampleData;

console.log('Default stringify (circular references removed):');
console.log(stringify(exampleData));

console.log('\nStringify with restored references (uses IIFE):');
console.log(stringify(exampleData, null, 2, { references: true }));

console.log('\nStringify with maxDepth:');
console.log(stringify(exampleData, null, null, { maxDepth: 2 }));

const replacerExample = stringify(['foo', 123, 'bar'], function (value, indent, stringify) {
  if (typeof value === 'string') {
    return '"' + value.toUpperCase() + '"';
  }
  return stringify(value);
});
console.log('\nStringify with custom replacer:');
console.log(replacerExample);

view raw JSON →