JavaScript Object Notation (JSON)
What is JSON?
Section titled “What is JSON?”JSON (JavaScript Object Notation) is a lightweight, text-based data format used to exchange information between systems. Despite its name, JSON is language-independent and works with virtually any programming language.
Why JSON is Popular
Section titled “Why JSON is Popular”- Human-readable - Easy to read and write
- Lightweight - Less verbose than XML
- Universal support - Supported by all modern programming languages
- Web-friendly - Native support in JavaScript and web browsers
- Simple syntax - Only 6 data types to learn
JSON Data Types
Section titled “JSON Data Types”JSON supports exactly 6 data types:
1. String
Section titled “1. String”Text enclosed in double quotes (single quotes not allowed).
"Hello World""Planet Mars""user@example.com"
json
2. Number
Section titled “2. Number”Integers or floating-point numbers (no quotes needed).
423.14159-170
json
3. Boolean
Section titled “3. Boolean”True or false values (no quotes needed).
truefalse
json
4. null
Section titled “4. null”Represents empty or no value.
null
json
5. Object
Section titled “5. Object”Collection of key-value pairs enclosed in curly braces {}
.
{ "name": "Earth", "diameter": 12742, "hasLife": true}
json
6. Array
Section titled “6. Array”Ordered list of values enclosed in square brackets []
.
["Mercury", "Venus", "Earth", "Mars"]
json
JSON Syntax Rules
Section titled “JSON Syntax Rules”- Keys must be strings (in double quotes)
- Values can be any of the 6 data types
- Comma separates key-value pairs and array items
- No trailing commas allowed
- No comments allowed in JSON
- Double quotes only (not single quotes)
✅ Valid JSON
Section titled “✅ Valid JSON”{ "planetName": "Jupiter", "moons": 79, "isGasGiant": true, "atmosphere": ["hydrogen", "helium"]}
json
❌ Invalid JSON
Section titled “❌ Invalid JSON”{ 'planetName': 'Jupiter', // Single quotes not allowed "moons": 79, // Trailing comma not allowed "isGasGiant": true, // This is a comment // Comments not allowed}
json
Building JSON Step by Step
Section titled “Building JSON Step by Step”Step 1: Simple Object
Section titled “Step 1: Simple Object”{ "name": "Mars"}
json
Step 2: Multiple Properties
Section titled “Step 2: Multiple Properties”{ "name": "Mars", "diameter": 6779, "hasLife": false}
json
Step 3: Adding an Array
Section titled “Step 3: Adding an Array”{ "name": "Mars", "diameter": 6779, "hasLife": false, "moons": ["Phobos", "Deimos"]}
json
Step 4: Nested Object
Section titled “Step 4: Nested Object”{ "name": "Mars", "diameter": 6779, "hasLife": false, "moons": ["Phobos", "Deimos"], "atmosphere": { "composition": "CO2", "pressure": 0.636 }}
json
JSON in REST APIs
Section titled “JSON in REST APIs”GET Response - Single Resource
Section titled “GET Response - Single Resource”{ "id": 123, "name": "Saturn", "diameter": 116460, "rings": true, "discoveredBy": "Ancient astronomers", "yearDiscovered": null}
json
GET Response - Collection
Section titled “GET Response - Collection”[ { "id": 1, "name": "Mercury", "diameter": 4879 }, { "id": 2, "name": "Venus", "diameter": 12104 }, { "id": 3, "name": "Earth", "diameter": 12742 }]
json
POST Request Body - Create Resource
Section titled “POST Request Body - Create Resource”{ "name": "Kepler-452b", "diameter": 16300, "distanceFromStar": 1.05, "isHabitable": true}
json
Error Response
Section titled “Error Response”{ "error": "Validation failed", "message": "Planet name is required", "code": "MISSING_REQUIRED_FIELD", "timestamp": "2024-01-15T10:30:00Z"}
json
Working with JSON in JavaScript
Section titled “Working with JSON in JavaScript”Parsing JSON String to Object
Section titled “Parsing JSON String to Object”// JSON string from API responseconst jsonString = '{"name": "Neptune", "moons": 14}';
// Convert JSON string to JavaScript objectconst planet = JSON.parse(jsonString);
console.log(planet.name); // Output: "Neptune"console.log(planet.moons); // Output: 14
javascript
Converting Object to JSON String
Section titled “Converting Object to JSON String”// JavaScript objectconst planet = { name: "Uranus", moons: 27, rings: true};
// Convert object to JSON stringconst jsonString = JSON.stringify(planet);
console.log(jsonString);// Output: {"name":"Uranus","moons":27,"rings":true}
javascript
Common JSON Mistakes to Avoid
Section titled “Common JSON Mistakes to Avoid”1. Using Single Quotes
Section titled “1. Using Single Quotes”// ❌ Wrong{ 'name': 'Mars' }
// ✅ Correct{ "name": "Mars" }
json
2. Trailing Commas
Section titled “2. Trailing Commas”// ❌ Wrong{ "name": "Venus", "hot": true,}
// ✅ Correct{ "name": "Venus", "hot": true}
json
3. Undefined Values
Section titled “3. Undefined Values”// ❌ Wrong - undefined is not valid JSON{ "name": "Pluto", "status": undefined}
// ✅ Correct - use null for empty values{ "name": "Pluto", "status": null}
json
4. Functions in JSON
Section titled “4. Functions in JSON”// ❌ Wrong - functions not allowed{ "name": "Earth", "getInfo": function() { return this.name; }}
// ✅ Correct - only data, no functions{ "name": "Earth", "description": "Third planet from the Sun"}
json
JSON vs Other Formats
Section titled “JSON vs Other Formats”JSON vs XML
Section titled “JSON vs XML”// JSON - concise and readable{ "planet": { "name": "Mars", "moons": 2 }}
json
<!-- XML - more verbose --><planet> <name>Mars</name> <moons>2</moons></planet>
xml
JSON vs URL Parameters
Section titled “JSON vs URL Parameters”// URL Parameters - limited and hard to readGET /api/planets?name=Mars&moons=2&hasLife=false
// JSON Body - structured and flexiblePOST /api/planets{ "name": "Mars", "moons": 2, "hasLife": false, "atmosphere": { "primary": "CO2", "secondary": "N2" }}
plaintext
Best Practices for JSON in APIs
Section titled “Best Practices for JSON in APIs”1. Use Consistent Naming
Section titled “1. Use Consistent Naming”// ✅ Good - consistent camelCase{ "planetName": "Jupiter", "moonCount": 79, "isGasGiant": true}
// ❌ Avoid - mixed naming styles{ "planet_name": "Jupiter", "moonCount": 79, "is-gas-giant": true}
json
2. Include Metadata for Collections
Section titled “2. Include Metadata for Collections”{ "planets": [ { "id": 1, "name": "Mercury" }, { "id": 2, "name": "Venus" } ], "total": 8, "page": 1, "limit": 2}
json
3. Use Meaningful Error Messages
Section titled “3. Use Meaningful Error Messages”{ "error": { "code": "VALIDATION_ERROR", "message": "Invalid planet data", "details": [ { "field": "diameter", "message": "Must be a positive number" } ] }}
json