JSON5 is an extension of JSON (JavaScript Object Notation) that aims to make it easier for humans to write and maintain. It adds several features to improve readability and reduce errors, while remaining a strict subset of JavaScript.
{
// This is a single-line comment
"name": "John Doe",
"age": 30,
"hobbies": [
"reading",
"cycling",
"photography", // Trailing comma is allowed
],
/* This is a
multi-line comment */
}
{
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, too',
"backwardsCompatible": "with JSON",
}
JSON5 offers several advantages over standard JSON syntax:
To use JSON5 in your projects, you'll need to use a JSON5 parser instead of a standard JSON parser. Here's an example using the official JSON5 library for JavaScript:
import JSON5 from 'json5'
const data = JSON5.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, too',
"backwardsCompatible": "with JSON",
}`)
console.log(data)
JSON5 extends the capabilities of JSON to make it more human-friendly and easier to maintain. While it's not a replacement for standard JSON in all scenarios, it can be a valuable tool for configuration files, data storage, and other use cases where readability and maintainability are priorities. When deciding whether to use JSON5, consider your project's requirements, the tools and libraries you're using, and the potential trade-offs in terms of performance and compatibility.