Understanding JSON Syntax in JavaScript
JSON Syntax in JavaScript JSON, which stands for JavaScript Object Notation, is a straightforward way to represent structured data. A single JSON document contains one JSON valu...
JSON Syntax in JavaScript
JSON, which stands for JavaScript Object Notation, is a straightforward way to represent structured data. A single JSON document contains one JSON value, which can be one of the following:
- An Object
- An Array
- A String
- A Number
- A Boolean
- Null
JSON Object Literals
Consider this JSON string. It contains a JSON object literal, structured using curly braces {}. An object includes one or more properties. These properties are organized as key/value pairs separated by commas. Key names are strings enclosed in double quotes, and the keys and values are separated by a colon.
A valid JSON data type must be used for values, which include:
- String:
"John" - Number:
42 - Boolean:
true - Null:
null - Object:
{"name": "John"} - Array:
[1, 2, 3]
It's a common misunderstanding to refer to a JSON object literal as simply a "JSON object." JSON is a data format in string form. Once a JSON string is converted into a JavaScript variable, it becomes a JavaScript object.
JSON Array Literals
In a JSON string, a JSON array literal is defined between square brackets []. An array can hold zero or more values, separated by commas.
Values within an array can also be any of the six JSON data types:
- String:
"John" - Number:
42 - Boolean:
true - Null:
null - Object:
{"name": "John"} - Array:
[1, 2, 3]
JSON Syntax Basics
JSON syntax is inspired by JavaScript object notation, but it is more restrictive:
- Curly braces
{}are used for objects. - Properties are name/value pairs.
- Commas separate properties.
- Square brackets
[]are used for arrays. - Strings must be in double quotes.
JSON enforces stricter syntax rules compared to JavaScript objects.
JSON Limitations
The following JavaScript features are not valid in JSON:
- Unquoted property names: Not allowed in JSON.
- Single quoted strings: Not permitted.
- Trailing commas: Not allowed.
- Comments: JSON does not support comments.
JSON Property Names and Strings
Property names in JSON must be strings, enclosed in double quotes. Similarly, JSON strings must use double quotes.
Whitespace
Whitespace, including spaces, tabs, and line breaks, is ignored outside of strings, making JSON easier to read.
Trailing Commas
JSON syntax does not permit a comma after the last property or array value.
Comments
JSON does not allow comments within the data.