JSON Syntax
JSON syntax is a small, strict set of rules for writing name/value pairs, objects, and arrays as text.
The Core Building Block: Name/Value Pairs
Every piece of data in a JSON object is written as a name/value pair: a name (also called a key), a colon, and a value. The name must be a string wrapped in double quotes, and multiple pairs inside an object are separated by commas.
Name/Value Pairs
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const data = {
"firstName": "Grace",
"lastName": "Hopper",
"yearsActive": 43
};
document.getElementById("demo").innerHTML = data.firstName + " " + data.lastName;
</script>
</body>
</html>Quoting Rules
JSON is strict about quoting. Keys must always use double quotes — single quotes are not valid JSON, even though they are valid in JavaScript object literals. String values must also use double quotes. Numbers, booleans, and null are written without any quotes at all.
- Keys: always double-quoted, e.g. "age": 30
- String values: always double-quoted, e.g. "status": "active"
- Numbers: no quotes, e.g. "age": 30
- Booleans: no quotes, lowercase only — true or false
- Null: no quotes, lowercase only — null
Objects and Arrays
An object is an unordered set of name/value pairs wrapped in curly braces { }. An array is an ordered list of values wrapped in square brackets [ ]. Arrays do not require names for each entry — just the values themselves, separated by commas.
An Object Containing an Array
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const data = {
"student": "Miguel",
"scores": [88, 92, 79, 95]
};
document.getElementById("demo").innerHTML = data.student + ": " + data.scores.join(", ");
</script>
</body>
</html>Objects and arrays can nest inside each other to any depth, which is what allows JSON to represent complex, real-world data like an order with a customer, a shipping address, and a list of line items.
Nested Structure
<!DOCTYPE html>
<html>
<body>
<h2>Result</h2>
<p id="demo"></p>
<script>
const data = {
"orderId": 4471,
"customer": { "name": "Priya", "vip": false },
"items": [
{ "sku": "A100", "qty": 2 },
{ "sku": "B240", "qty": 1 }
]
};
document.getElementById("demo").innerHTML = "Order " + data.orderId + " for " + data.customer.name;
</script>
</body>
</html>Commas and Trailing Commas
Commas separate entries in both objects and arrays, but JSON does not allow a trailing comma after the last entry — a common mistake when converting from JavaScript, where trailing commas are permitted.
Exercise: JSON Syntax
In valid JSON, how must an object's keys (names) be written?