Chapter 2

JSON Objects

Learn the basic syntax and data types of JSON objects

Basic Structure of JSON Objects

A JSON object is an unordered collection of key-value pairs. Data is enclosed in {}, each key-value pair is separated by a colon :, and multiple key-value pairs are separated by commas ,.

Example
{
  "name": "John",
  "age": 30,
  "isEmployed": true,
  "salary": null
}

Supported Data Types in JSON

String
"name": "John"

Must be enclosed in double quotes

Number
"age": 30
"price": 99.99

Integer or floating point

Boolean
"isActive": true
"isDeleted": false

true or false (lowercase)

Null
"middleName": null

Represents empty value (lowercase)

Object
"address": {
  "city": "New York",
  "street": "Broadway"
}

Nested objects

Array
"skills": [
  "JavaScript",
  "Python"
]

Ordered list of values

Key Rules for JSON Objects

Keys Must Use Double Quotes

JSON object keys must be double-quoted strings. Single quotes or unquoted keys are not allowed.

✅ Correct

"name": "John"

❌ Wrong

name: "John"

Key-Value Pairs Separated by Colons

Keys and values are separated by colons :.

"key": "value"  ✅
"key" : "value" ✅ (spaces optional)

Multiple Key-Value Pairs Separated by Commas

Multiple key-value pairs are separated by commas ,, but no trailing comma after the last pair.

✅ Correct

{"a": 1, "b": 2}

❌ Wrong

{"a": 1, "b": 2,}

Keys Should Be Unique

Although the JSON standard allows duplicate keys, most parsers only keep the last value. It's recommended to avoid duplicate key names.

Interactive Exercise

Create a JSON object describing yourself in the editor below, including the following properties:

  • name (string): Your name
  • age (number): Your age
  • hobbies (array): Your hobbies
  • isStudent (boolean): Are you a student

Common Mistakes

❌ Using Single Quotes

{'name': 'John'}

JSON keys and string values must use double quotes, single quotes are not allowed.

❌ Unquoted Keys

{name: "John"}

This looks like a JavaScript object literal, but it is invalid in JSON.

❌ Trailing Comma

{"name": "John", "age": 30,}

JSON does not allow a comma after the last property.

❌ Comments

{"name": "John", /* comment */ "age": 30}

Standard JSON does not support comments.

Chapter Quiz

Exercise: Find errors in the following JSON
{
  name: "Bob",
  'age': 28,
  "city": "London",
  "email": null,
}
A. name is not double-quoted
B. age uses single quotes
C. There is a trailing comma at the end
D. All of the above