The JavaScript Object Notation and how it is used.
JSON
- The JavaScript Object Notation or JSON is a lightweight text format for exchanging object data between applications (which may or may not be implemented in JavaScript).
- JSON uses the JavaScript syntax for object and array literals, with a few restrictions:
- Values are object literals, array literals, strings, floating-point numbers, and the values true, false, and null.
- All strings are delimited by double quotes, not single quotes.
- All property names are delimited by double quotes.
- There are no trailing commas or skipped elements.
An example of a JSON string is:
{ "name": "Harry Smith", "age": 42, "lucky numbers": [17, 29], "lucky": false }
Note of Caution: JSON.stringify drops object properties whose value is undefined, and it turns array elements with undefined values to null. For example,
JSON.stringify({ name: ['Harry', undefined, 'Smith'], age: undefined }) is the string '{"name":["Harry",null,"Smith"]}'.
Some programmers use the JSON.stringify method for logging. A logging command
console.log(`harry=${harry}`)
gives you a useless message
harry=[object Object]
A remedy is to call JSON.stringify:
console.log(`harry=${JSON.stringify(harry)}`)
Note that this problem only occurs with strings that contain objects. If you log an object by itself, the console displays it nicely. An easy alternative is to log the names and values separately:
console.log('harry=', harry, 'sally=', sally)
Or even easier, put them into an object:
console.log({harry, sally}) // Logs the object { harry: { . . . }, sally: { . . . } }
Rapidly move from another programming language and quickly get productive with today's version of JavaScript with Modern JavaScript for the Impatient.