JSON5 Format: Comments, Trailing Commas, and Parsing in JavaScript

JSON5 is a superset of JSON that relaxes the strict JSON syntax to make configuration files more human-friendly. It adds comments, trailing commas, unquoted keys, single-quoted strings, hexadecimal numbers, Infinity, NaN, and multiline strings — while remaining fully backward-compatible with standard JSON.

Have a JSON file that's almost valid but not quite? Paste it into Jsonic's JSON Formatter to spot and fix errors in standard JSON instantly.

Validate JSON Free

What is JSON5?

JSON5 was created to address a common pain point: standard JSON is great for data interchange but uncomfortable to write by hand. Config files need comments to explain settings; developers expect trailing commas so adding a new property doesn't require editing the previous line; property keys in JavaScript objects don't need quotes, so requiring them in JSON feels artificial.

JSON5 solves all of this without breaking compatibility. The six main additions are:

  • Comments — single-line (//) and block (/* */)
  • Trailing commas — in objects and arrays
  • Unquoted keys — any valid ECMAScript identifier works as a key
  • Single-quoted strings'like this' as well as "like this"
  • Extended numbers — hexadecimal (0xDEAD), +Infinity, -Infinity, NaN, leading/trailing decimal point (.5, 5.)
  • Multiline strings — a backslash before a newline continues the string

Here is a complete JSON5 document that uses all of these features. None of this is valid standard JSON:

// JSON5 example — none of this is valid in standard JSON
{
  /* Basic info */
  name: "Alice",               // unquoted key
  'nickname': 'Ali',           // single-quoted key and value
  score: 0xDEADBEEF,           // hexadecimal number
  ratio: .5,                   // leading decimal point
  maxValue: +Infinity,         // Infinity
  flags: [
    true,
    false,
    null,                      // trailing comma in array
  ],
  address: {
    street: "123 Main St",
    city: "Springfield",       // trailing comma in object
  },
  bio: "Line one \
  continued on line two",      // multiline string (backslash + newline)
}

JSON5 vs JSON feature comparison

The table below shows every syntax difference between JSON5 and standard JSON. JSON5 is a strict superset, so the JSON column is always a subset of what JSON5 supports.

FeatureJSON5JSON
Single-line comments (//)YesNo
Block comments (/* */)YesNo
Trailing commas in objectsYesNo
Trailing commas in arraysYesNo
Unquoted object keysYesNo
Single-quoted stringsYesNo
Hexadecimal numbers (0x…)YesNo
Infinity and NaNYesNo
Leading decimal point (.5)YesNo
Trailing decimal point (5.)YesNo
Multiline strings (backslash + newline)YesNo
Double-quoted stringsYesYes
Quoted object keysYesYes
null, true, falseYesYes
Nested objects and arraysYesYes
Unicode escape sequencesYesYes

Parsing JSON5 in Node.js with the json5 npm package

The official JSON5 implementation is published on npm as json5. The API mirrors the built-in JSON object: JSON5.parse() and JSON5.stringify().

Install the package:

npm install json5

Parse a JSON5 string in CommonJS:

const JSON5 = require('json5')

const data = JSON5.parse(`{
  // server config
  host: 'localhost',
  port: 3000,
  debug: true,
}`)

console.log(data.host)  // 'localhost'
console.log(data.port)  // 3000

Parse with ES modules syntax:

import JSON5 from 'json5'

const data = JSON5.parse(`{
  host: 'localhost',
  port: 3000,
}`)

console.log(data.host)  // 'localhost'

JSON5.parse() throws a SyntaxError on invalid input, just like JSON.parse(). Wrap it in a try/catch block when processing untrusted strings.

Reading a JSON5 file in Node.js

The most common use case for JSON5 is loading configuration files. Read the file with Node's fs module, then parse it with JSON5.parse():

const fs = require('fs')
const JSON5 = require('json5')

// Read and parse a .json5 config file
const raw = fs.readFileSync('config.json5', 'utf8')
const config = JSON5.parse(raw)

console.log(config.host)
console.log(config.port)

Async version with fs.promises:

const fs = require('fs/promises')
const JSON5 = require('json5')

async function loadConfig(path) {
  const raw = await fs.readFile(path, 'utf8')
  return JSON5.parse(raw)
}

const config = await loadConfig('config.json5')

A typical config.json5 file might look like this:

// config.json5
{
  // Database settings
  database: {
    host: 'localhost',
    port: 5432,
    name: 'myapp',
  },

  // Server settings
  server: {
    port: 3000,
    debug: true,  // disable in production
  },
}

Converting JSON5 to standard JSON

Parse the JSON5 string into a JavaScript object, then serialize it back to standard JSON with JSON.stringify(). This strips comments, trailing commas, unquoted keys, and all other JSON5-only syntax:

const JSON5 = require('json5')

const json5String = `{
  // user record
  name: 'Alice',
  score: .5,
  tags: ['admin', 'user',],  // trailing comma
}`

const data = JSON5.parse(json5String)
const jsonString = JSON.stringify(data, null, 2)

console.log(jsonString)
// {
//   "name": "Alice",
//   "score": 0.5,
//   "tags": ["admin", "user"]
// }

This approach is useful when you author config files in JSON5 but need to send or store them as standard JSON — for example, when writing to an API or a database that only accepts strict JSON.

Need to format or validate standard JSON interactively? The Jsonic JSON Formatter handles standard JSON in the browser without any setup.

Using JSON5 in the browser with webpack

The browser's native JSON.parse() does not support JSON5 syntax. To use JSON5 in a frontend project, either bundle the json5 package with a bundler, or configure webpack to import .json5 files as modules directly:

// webpack.config.js — load .json5 files as modules
module.exports = {
  module: {
    rules: [
      {
        test: /\.json5$/,
        type: 'json',
        parser: { parse: require('json5').parse },
      },
    ],
  },
}

With this rule in place, you can import .json5 files as if they were plain objects:

// Treated as a JS module by webpack
import config from './config.json5'

console.log(config.host)  // 'localhost'

Vite does not have built-in JSON5 support, but the vite-plugin-json5 community plugin provides the same capability.

TypeScript support

The json5 package ships its own TypeScript declarations. Use the generic overload of JSON5.parse() to get a typed result:

import JSON5 from 'json5'

interface ServerConfig {
  host: string
  port: number
  debug: boolean
}

const raw = `{
  host: 'localhost',
  port: 3000,
  debug: true,
}`

const config = JSON5.parse<ServerConfig>(raw)

// TypeScript knows config.host is a string
console.log(config.host.toUpperCase())  // 'LOCALHOST'

For importing .json5 files as typed modules, add a declaration file to your project:

// json5.d.ts (put in your src/ folder)
declare module '*.json5' {
  const value: unknown
  export default value
}

When to use JSON5 — and when not to

JSON5 is a good fit in specific scenarios. It is not a universal replacement for standard JSON.

Use JSON5 when:

  • Writing configuration files that developers read and edit by hand — comments explain settings, trailing commas let you add lines without touching the previous one.
  • Internal tooling where your whole stack is Node.js and the json5 package is already available.
  • Replacing JSONC when you also need unquoted keys or hexadecimal numbers (e.g., memory addresses or bitmask flags in config).

Avoid JSON5 when:

  • API payloads — HTTP servers and clients expect standard JSON. Sending JSON5 to a REST or GraphQL API will cause a parse error on the other end.
  • Browser JSON.parse() — the native parser does not understand JSON5. You must always include the json5 library.
  • Cross-language projects — JSON5 parsers exist in Python, Go, Rust, and others, but they are far less common than standard JSON parsers. Team members may be unfamiliar with the format.
  • Data storage — databases, message queues, and log pipelines generally expect standard JSON. Convert to JSON with JSON.stringify() before storing.
Use caseRecommended formatReason
Hand-authored config filesJSON5 or TOMLComments and trailing commas improve maintainability
VS Code / editor settingsJSONCEditor natively supports JSONC; full JSON5 is not needed
REST API request/responseStandard JSONUniversal parser support across languages and clients
Database storageStandard JSONDatabases parse and index standard JSON natively
Node.js build toolingJSON5json5 npm package is a single dependency away

Frequently asked questions

What is JSON5?

JSON5 is a superset of JSON that extends the syntax with comments, trailing commas, unquoted keys, single-quoted strings, hexadecimal numbers, Infinity, NaN, and multiline strings. It was designed for human-authored configuration files where standard JSON's strictness creates unnecessary friction. Every valid JSON document is also valid JSON5.

Is JSON5 compatible with standard JSON?

Yes — JSON5 is a strict superset of JSON. Any valid JSON file can be parsed by a JSON5 parser without changes. The reverse is not true: a JSON5 file that uses comments or trailing commas will fail if you try to parse it with the built-in JSON.parse() function.

How do I parse JSON5 in JavaScript?

Install the json5 package from npm and use JSON5.parse(string). The API is identical to the native JSON.parse(). For Node.js: npm install json5, then const JSON5 = require('json5'). For ES modules: import JSON5 from 'json5'.

Can I use JSON5 in the browser?

Yes, but you must bundle the json5 package — the browser's native JSON.parse() does not support JSON5 syntax. With webpack you can also configure a loader rule so .json5 files are imported directly as JavaScript objects. Alternatively, load json5 from a CDN and call JSON5.parse() in your scripts.

What is the difference between JSON5 and JSONC?

JSONC (JSON with Comments) is a minimal extension: it adds only // and /* */ comments plus trailing commas. JSON5 goes much further with unquoted keys, single quotes, hex numbers, Infinity, NaN, and multiline strings. VS Code uses JSONC for its settings.json and tsconfig.json files.

Should I use JSON5 for API responses?

No. Use standard JSON for any data that crosses a network boundary or is consumed by a system outside your control. Most HTTP clients, server frameworks, and programming languages parse standard JSON natively. Sending JSON5 to a server or API that expects standard JSON will cause a parse error.

Format and validate your JSON

Working with standard JSON files? Paste them into Jsonic's JSON Formatter to format, validate, and fix syntax errors in seconds — no installation needed.

Open JSON Formatter