JSON6 for JavaScript

The complete guide to using JSON6 in JavaScript and Node.js projects.

TL;DR: Install with npm install json6, import with import JSON6 from 'json6', then use JSON6.parse() and JSON6.stringify() just like the native JSON methods.

Installation

The official JSON6 package is available on npm and is the reference implementation maintained by the JSON6 community.

npm

npm install json6

Yarn

yarn add json6

pnpm

pnpm add json6

Bun

bun add json6

65M+

Weekly downloads

~6KB

Minified size

0

Dependencies

Basic Usage

ES Modules (Recommended)

import JSON6 from 'json6'; // Parse JSON6 string to JavaScript object const obj = JSON6.parse(`{ // This is a comment name: 'my-app', version: '1.0.0', features: [ 'comments', 'trailing commas', ], }`); console.log(obj.name); // 'my-app' console.log(obj.features[0]); // 'comments'

CommonJS

const JSON6 = require('json6'); const config = JSON6.parse(configString); console.log(config);

Stringify JavaScript to JSON6

const obj = { name: 'my-app', debug: true, ports: [3000, 3001], }; // Convert to JSON6 string const json6String = JSON6.stringify(obj, null, 2); console.log(json6String); /* { name: 'my-app', debug: true, ports: [ 3000, 3001, ], } */

API Reference

The JSON6 API mirrors the native JSON API for familiarity, with some additional options.

JSON6.parse(text, reviver?)

Parses a JSON6 string and returns the corresponding JavaScript value.

Parameters

Parameter Type Description
text string The JSON6 string to parse
reviver function? Optional transform function called for each key-value pair

Example with Reviver

// Convert date strings to Date objects const obj = JSON6.parse(`{ created: '2024-01-15T10:30:00Z', }`, (key, value) => { if (key === 'created') { return new Date(value); } return value; }); console.log(obj.created instanceof Date); // true

JSON6.stringify(value, replacer?, space?)

Converts a JavaScript value to a JSON6 string.

Parameters

Parameter Type Description
value any The value to convert
replacer function | array? Transform function or array of property names to include
space number | string? Indentation (number of spaces or string)

Options Object (Alternative)

JSON6.stringify also accepts an options object as the second parameter:

const str = JSON6.stringify(obj, { replacer: null, space: 2, quote: "'", // Use single quotes });

Stringify Options

Option Type Default Description
replacer function | array null Same as JSON.stringify replacer
space number | string null Indentation level
quote string "'" Quote character for strings

Reading JSON6 Files

Common patterns for loading JSON6 configuration files in Node.js.

Synchronous (Simple)

import JSON6 from 'json6'; import { readFileSync } from 'fs'; function loadConfig(path) { const content = readFileSync(path, 'utf8'); return JSON6.parse(content); } const config = loadConfig('./config.json6'); console.log(config);

Asynchronous (Recommended for Large Files)

import JSON6 from 'json6'; import { readFile } from 'fs/promises'; async function loadConfig(path) { const content = await readFile(path, 'utf8'); return JSON6.parse(content); } // Usage const config = await loadConfig('./config.json6');

With Error Handling

import JSON6 from 'json6'; import { readFileSync, existsSync } from 'fs'; function loadConfig(path, defaults = {}) { if (!existsSync(path)) { console.warn(`Config not found: ${path}, using defaults`); return defaults; } try { const content = readFileSync(path, 'utf8'); return { ...defaults, ...JSON6.parse(content) }; } catch (error) { if (error instanceof SyntaxError) { console.error(`Invalid JSON6 in ${path}:`, error.message); } throw error; } } const config = loadConfig('./config.json6', { debug: false, port: 3000, });

Using require() Hook (Node.js)

Register JSON6 as a require handler to import .json6 files directly:

// At application startup require('json6/lib/register'); // Now you can require .json6 files const config = require('./config.json6');

TypeScript Support

The JSON6 package includes built-in TypeScript type definitions. No additional @types package needed.

Basic TypeScript Usage

import JSON6 from 'json6'; interface AppConfig { name: string; version: string; debug: boolean; port: number; } const configString = `{ name: 'my-app', version: '1.0.0', debug: true, port: 3000, }`; // Type assertion const config = JSON6.parse(configString) as AppConfig; console.log(config.name); // TypeScript knows this is a string console.log(config.port); // TypeScript knows this is a number

Type-Safe Config Loader

import JSON6 from 'json6'; import { readFileSync } from 'fs'; interface DatabaseConfig { host: string; port: number; database: string; ssl: boolean; } interface AppConfig { name: string; database: DatabaseConfig; } function loadConfig<T>(path: string): T { const content = readFileSync(path, 'utf8'); return JSON6.parse(content) as T; } const config = loadConfig<AppConfig>('./config.json6'); console.log(config.database.host); // Fully typed

With Zod Validation

import JSON6 from 'json6'; import { z } from 'zod'; import { readFileSync } from 'fs'; const ConfigSchema = z.object({ name: z.string(), port: z.number().int().positive(), debug: z.boolean().default(false), }); type Config = z.infer<typeof ConfigSchema>; function loadConfig(path: string): Config { const content = readFileSync(path, 'utf8'); const parsed = JSON6.parse(content); return ConfigSchema.parse(parsed); // Validates at runtime } const config = loadConfig('./config.json6'); // config is fully typed AND validated

Browser Usage

JSON6 works in all modern browsers. Here are different ways to use it client-side.

Via CDN (Quick Start)

<script src="https://unpkg.com/json6@2/dist/index.min.js"></script> <script> // JSON6 is available as a global const config = JSON6.parse(`{ theme: 'dark', sidebar: true, // Show sidebar by default }`); console.log(config.theme); // 'dark' </script>

ES Module via CDN

<script type="module"> import JSON6 from 'https://unpkg.com/json6@2/dist/index.min.mjs'; const config = JSON6.parse(`{ debug: true }`); console.log(config); </script>

Fetch Remote JSON6 File

async function loadRemoteConfig(url) { const response = await fetch(url); const text = await response.text(); return JSON6.parse(text); } // Usage loadRemoteConfig('/config.json6').then(config => { console.log(config); });

Bundler Integration

Import JSON6 files directly in your bundled applications using loader plugins.

Vite

Vite supports JSON6 out of the box for config files. For importing JSON6 in source:

// vite.config.js import json6Plugin from 'vite-plugin-json6'; export default { plugins: [json6Plugin()], };
// Now import JSON6 files directly import config from './config.json6'; console.log(config);

webpack

Use the json6-loader for webpack:

npm install json6-loader --save-dev
// webpack.config.js module.exports = { module: { rules: [ { test: /\.json6$/, loader: 'json6-loader', type: 'javascript/auto', }, ], }, };
// Import JSON6 files import config from './config.json6';

Rollup

Use @rollup/plugin-json with JSON6 parsing:

// rollup.config.js import json from '@rollup/plugin-json'; export default { plugins: [ json({ // Include JSON6 files include: ['**/*.json', '**/*.json6'], }), ], };

esbuild

Create a JSON6 loader plugin:

import * as esbuild from 'esbuild'; import JSON6 from 'json6'; import { readFile } from 'fs/promises'; const json6Plugin = { name: 'json6', setup(build) { build.onLoad({ filter: /\.json6$/ }, async (args) => { const text = await readFile(args.path, 'utf8'); return { contents: JSON.stringify(JSON6.parse(text)), loader: 'json', }; }); }, }; await esbuild.build({ plugins: [json6Plugin], });

Converting Between Formats

JSON6 to JSON

import JSON6 from 'json6'; const json6String = `{ // Config with comments name: 'app', debug: true, }`; // Parse JSON6, stringify as JSON const obj = JSON6.parse(json6String); const jsonString = JSON.stringify(obj, null, 2); console.log(jsonString); /* { "name": "app", "debug": true } */

JSON to JSON6

import JSON6 from 'json6'; const jsonString = `{ "name": "app", "debug": true }`; // Parse JSON (or JSON6), stringify as JSON6 const obj = JSON.parse(jsonString); const json6String = JSON6.stringify(obj, null, 2); console.log(json6String); /* { name: 'app', debug: true, } */

Best Practices

Use .json6 Extension

Name your files with .json6 extension for proper syntax highlighting and to signal that JSON6 features are used.

Document with Comments

Take advantage of comments to explain non-obvious settings, default values, and environment-specific configurations.

Validate Configuration

Use runtime validation (Zod, Yup, Joi) to ensure parsed configuration matches expected schema, especially for user-provided configs.

Cache Parsed Results

Parse configuration files once at startup and cache the result. Don't re-parse on every access.

Use Trailing Commas

Always include trailing commas for cleaner diffs when adding or removing items in version control.

Ready to Use JSON6?

Explore more examples or check out other language guides.