or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-json5

JSON5 provides parsing and serialization functionality for the JSON5 data interchange format, which is a superset of JSON that includes ECMAScript 5.1 syntax enhancements.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/json5@2.2.x

To install, run

npx @tessl/cli install tessl/npm-json5@2.2.0

index.mddocs/

JSON5

JSON5 is a JavaScript library that provides parsing and serialization functionality for the JSON5 data interchange format. JSON5 is a superset of JSON that includes ECMAScript 5.1 syntax enhancements, making configuration files and data structures more human-readable and maintainable.

Package Information

  • Package Name: json5
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install json5

Core Imports

import { parse, stringify } from 'json5';

For CommonJS:

const JSON5 = require('json5');
// Access via: JSON5.parse, JSON5.stringify

Basic Usage

import { parse, stringify } from 'json5';

// Parse JSON5 string
const data = parse(`{
  // comments are allowed
  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',],
}`);

// Convert JavaScript value to JSON5 string
const json5String = stringify(data, null, 2);

Capabilities

JSON5 Parsing

Parses a JSON5 string, constructing the JavaScript value or object described by the string.

/**
 * Parses a JSON5 string, constructing the JavaScript value or object described
 * by the string.
 * @template T The type of the return value.
 * @param text The string to parse as JSON5.
 * @param reviver A function that prescribes how the value originally produced
 * by parsing is transformed before being returned.
 * @returns The JavaScript value converted from the JSON5 string.
 */
function parse<T = any>(
    text: string,
    reviver?: ((this: any, key: string, value: any) => any) | null,
): T

Usage Examples:

import { parse } from 'json5';

// Basic parsing
const config = parse(`{
  name: 'MyApp',
  version: '1.0.0',
  debug: true,
}`);

// With reviver function
const data = parse(`{
  created: "2023-01-01",
  count: "42"
}`, (key, value) => {
  if (key === 'created') return new Date(value);
  if (key === 'count') return parseInt(value);
  return value;
});

JSON5 Stringification

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.

/**
 * Converts a JavaScript value to a JSON5 string.
 * @param value The value to convert to a JSON5 string.
 * @param replacer A function that alters the behavior of the stringification
 * process. If this value is null or not provided, all properties of the object
 * are included in the resulting JSON5 string.
 * @param 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.
 * @returns The JSON5 string converted from the JavaScript value.
 */
function stringify(
    value: any,
    replacer?: ((this: any, key: string, value: any) => any) | null,
    space?: string | number | null,
): string

/**
 * Converts a JavaScript value to a JSON5 string.
 * @param value The value to convert to a JSON5 string.
 * @param replacer An array of String and Number objects that serve as a
 * allowlist 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.
 * @param 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.
 * @returns The JSON5 string converted from the JavaScript value.
 */
function stringify(
    value: any,
    replacer: (string | number)[],
    space?: string | number | null,
): string

/**
 * Converts a JavaScript value to a JSON5 string.
 * @param value The value to convert to a JSON5 string.
 * @param options An object specifying options.
 * @returns The JSON5 string converted from the JavaScript value.
 */
function stringify(value: any, options: StringifyOptions): string

Usage Examples:

import { stringify } from 'json5';

const data = {
  name: 'MyApp',
  version: '1.0.0',
  debug: true,
  features: ['auth', 'api', 'ui']
};

// Basic stringification
const json5 = stringify(data);

// With formatting
const formatted = stringify(data, null, 2);

// With replacer function
const filtered = stringify(data, (key, value) => {
  if (key === 'debug') return undefined; // exclude debug
  return value;
}, 2);

// With property allowlist
const limited = stringify(data, ['name', 'version'], 2);

// With options object (including custom quote character)
const customQuotes = stringify(data, {
  space: 2,
  quote: "'"
});

Node.js require() Support

Enable JSON5 file support in Node.js require() statements by registering the .json5 file extension.

/**
 * Register JSON5 file extension with Node.js require() system.
 * This extends Node.js to automatically parse .json5 files when required.
 */
require('json5/lib/register');

Usage Example:

// Register JSON5 support
require('json5/lib/register');

// Now you can require JSON5 files directly
const config = require('./config.json5');

Command Line Interface

JSON5 provides a CLI tool for converting JSON5 to JSON and validating JSON5 syntax.

Installation:

npm install --global json5

Usage:

json5 [options] <file>

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

CLI 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
  • -c, --convert: (Legacy) Convert input file to .json extension when no output file specified
  • -V, --version: Output the version number
  • -h, --help: Output usage information

Examples:

# Convert JSON5 file to JSON
json5 config.json5

# Convert with formatting
json5 -s 2 config.json5

# Validate JSON5 syntax
json5 -v config.json5

# Convert and save to file
json5 -o config.json config.json5

# Convert and auto-save as .json file (legacy option)
json5 -c config.json5

Types

interface StringifyOptions {
    /**
     * A function that alters the behavior of the stringification process, or an
     * array of String and Number objects that serve as a allowlist 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.
     */
    replacer?:
        | ((this: any, key: string, value: any) => any)
        | (string | number)[]
        | null

    /**
     * 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.
     */
    space?: string | number | null

    /**
     * A String representing the quote character to use when serializing
     * strings.
     */
    quote?: string | null
}

JSON5 Format Features

JSON5 extends JSON with the following ECMAScript 5.1 features:

Objects

  • Object keys may be unquoted identifiers
  • Objects may have trailing commas

Arrays

  • Arrays may have trailing commas

Strings

  • Strings may be single quoted
  • Strings may span multiple lines by escaping newlines
  • Strings may include character escapes

Numbers

  • Numbers may be hexadecimal (0x...)
  • Numbers may have leading or trailing decimal points
  • Numbers may be IEEE 754 positive infinity, negative infinity, and NaN
  • Numbers may begin with an explicit plus sign

Comments

  • Single-line comments (//) and multi-line comments (/* */) are allowed

White Space

  • Additional white space characters are allowed

Error Handling

Both parse() and stringify() functions may throw errors:

  • Parse errors: Thrown when JSON5 syntax is invalid
  • Stringify errors: Thrown when values cannot be serialized (e.g., circular references)
  • CLI errors: Exit codes indicate validation or conversion failures

Always wrap JSON5 operations in try-catch blocks for production usage:

import { parse, stringify } from 'json5';

try {
  const data = parse(json5String);
  const output = stringify(data);
} catch (error) {
  console.error('JSON5 operation failed:', error.message);
}