en.javascript.info
en.javascript.info copied to clipboard
Added examples of typical errors in JSON
JSON methods, toJSON
let json = `{
*!*name*/!*: "John", // mistake: property name without quotes
"surname": *!*'Smith'*/!*, // mistake: single quotes in value (must be double)
*!*'isAdmin'*/!*: false, // mistake: single quotes in key (must be double)
"birthday": *!*new Date(2000, 2, 3)*/!*, // mistake: no "new" is allowed, only bare values
@@"gender": "male"*!* */!* // mistake: missing comma after non-last property @@
@@"friends": [0,1,2,3]*!*,*/!* // mistake: there should not be a comma after the last property @@
}`;
In practice, many novice developers, following the rule that in JavaScript there can be a "trailing comma" in an object, try to reproduce the same in JSON. But a trailing comma in JSON makes it invalid. This is a very widespread stuff, so I think we should add such an example to "typical mistakes".
Also, many people forget that a comma should be after each property except the last one, which also causes JSON to become invalid. I also added such an example.