JavaScript object to JSON: what changes
A JavaScript object literal and JSON look alike but JSON is stricter: keys must be in double quotes, strings too, no trailing commas, no comments and no code. Configuration pasted from a source file, a console.log output or documentation is usually a JavaScript object, not JSON, and JSON.parse refuses it. The converter reads the object with a JSON5 parser, so it understands everything JavaScript allows in an object literal, and writes strict JSON.
This page opens the tool in the JavaScript to JSON direction, with a sample config in it.
A real conversion
// A config pasted from a source file
const config = {
name: 'stdlib',
port: 0x1F90,
debug: true,
tags: ['a', "b",],
limits: { max: 10, ratio: .5, },
'content-type': 'text/plain',
};becomes:
{
"name": "stdlib",
"port": 8080,
"debug": true,
"tags": [
"a",
"b"
],
"limits": {
"max": 10,
"ratio": 0.5
},
"content-type": "text/plain"
}Feature by feature
| JavaScript | JSON (minified) | What it shows |
|---|---|---|
{ name: 1 } | {"name":1} | unquoted key |
{ 'name': 'x' } | {"name":"x"} | single quotes |
{ a: [1, 2,], } | {"a":[1,2]} | trailing commas |
{ a: 1, /* note */ b: 2 } | {"a":1,"b":2} | comments |
{ n: 0x1F, m: .5, p: +3 } | {"n":31,"m":0.5,"p":3} | hex, leading-dot and plus numbers |
export default { id: 7 }; | {"id":7} | an export or const wrapper |
Never executed
- The text is parsed as data. Anything that would need to run (a function, new Date(), a variable, a template literal with ${}) is refused with the line and column of the problem, instead of being evaluated.
- undefined has no JSON form and is dropped from objects; NaN and Infinity become null, and the tool warns when that happens.
- Single-quoted strings keep their content: a ' inside "it's" is not escaped in JSON, a " inside a single-quoted string is.
The way back
The same tool writes JSON as a JavaScript object, with single or double quotes, as const, let, export or module.exports, and quotes only the keys that need it:
const config = {
name: 'stdlib',
port: 8080,
debug: true,
tags: ['a', 'b'],
limits: {
max: 10,
ratio: 0.5
},
'content-type': 'text/plain'
};How to use the converter
- Paste the object, with or without the const or export in front.
- Choose the indentation (2, 4, tab or minified).
- Copy the JSON, or download it as a file.
Frequently asked questions
Why does JSON.parse fail on my JavaScript object?
Because JSON requires double-quoted keys and strings and allows no trailing commas, comments or single quotes. Convert it here and parse the result.
What is JSON5?
A superset of JSON that adopts the object syntax of JavaScript: comments, unquoted keys, single quotes, trailing commas and more number formats. It is used in some config files; every JSON5 document converts to plain JSON here.
Is my code executed or uploaded?
Neither. The text is parsed as data in your browser, so a pasted object cannot run anything and never leaves the page.