toolhq.io

All posts
4 min readby Jameel Haider

JSON5 vs JSON: what it adds and when to use it

Strict JSON is deliberately minimal. No comments, no trailing commas, every key wrapped in double quotes. That strictness is a feature for data on the wire, but it makes JSON awkward for files a human edits by hand, like config files. JSON5 is a superset that loosens those rules for the editing case.

What JSON5 adds

JSON5 keeps everything valid JSON and layers on conveniences that developers expect from JavaScript source:

  • Comments. Both // line and /* block */ styles work.
  • Trailing commas. The last item in an object or array can end with a comma, so reordering lines does not break the file.
  • Unquoted keys. Object keys that are valid identifiers can skip the quotes.
  • Single quotes. Strings can use ' or ", and strings can span multiple lines with a line continuation.
  • Extra number formats. Hex numbers, leading or trailing decimal points, and Infinity or NaN.

A JSON5 file reads much more like a JavaScript object literal:

{
  // service endpoint
  host: 'api.example.com',
  port: 443,
  retries: 3,  // trailing comma is fine
}

When it is safe to use

Use JSON5 only where you control both the writer and the reader. Good fits are local config files, fixtures, and documents consumed by a tool that explicitly parses JSON5, such as some bundlers and the TypeScript tsconfig.json family, which allow comments.

The rule that saves you grief: browsers, HTTP APIs, and JSON.parse expect strict JSON. A JSON5 document sent as a request body or response will fail to parse on the other side, because JSON.parse does not understand comments, trailing commas, or unquoted keys. There is no JSON5 reader built into the browser or into most standard libraries, so it is always an opt in dependency.

Converting between the two

The practical workflow is to author in JSON5 for readability, then emit strict JSON for anything that crosses a network boundary. Stripping comments and trailing commas and quoting keys produces a valid JSON document with identical data.

If you are unsure whether a file is already strict, paste it into the JSON Formatter and watch for a parse error. The tool runs entirely in your browser, so the input never leaves your device, which matters when the file holds config that mentions internal hosts or keys. A clean format means the document is valid strict JSON; an error usually points straight at a comment or a trailing comma.

A related question comes up often: can you use comments in JSON? The short answer is no in strict JSON, which is exactly the gap JSON5 fills.

The takeaway: reach for JSON5 when a human edits the file and a JSON5 aware tool reads it. Everywhere a machine talks to a machine, keep it strict and validate before you ship.