JSON Tutorial for Beginners
Learn JSON from scratch with simple, step-by-step examples. No prior experience required.
Table of Contents
1. What is JSON?
JSON stands for JavaScript Object Notation. It's a simple way to store and exchange data using plain text that both humans and computers can easily read.
Think of JSON like a standardized form. Just as a form has labeled fields (Name: ___, Age: ___), JSON has labeled data:
{
"name": "John",
"age": 30
}
That's it! You just saw your first JSON. It describes a person with a name "John" and age 30.
2. Why Learn JSON?
JSON is everywhere in modern software development:
- Web APIs: When websites talk to servers, they usually exchange JSON data
- Configuration Files: Many apps store settings in JSON files
- Databases: NoSQL databases like MongoDB store data as JSON
- Mobile Apps: iOS and Android apps use JSON for data exchange
If you're learning web development, mobile development, or working with APIs, you'll encounter JSON daily.
3. Your First JSON
Let's build JSON step by step. We'll describe a book:
Step 1: Start with curly braces
All JSON objects start and end with curly braces { }
{ }
Step 2: Add a property
Properties have a name (key) and a value, separated by a colon:
{
"title": "The Great Gatsby"
}
Step 3: Add more properties
Separate multiple properties with commas:
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": 1925,
"available": true
}
4. JSON Syntax Rules
JSON has strict rules. Break any of these and your JSON becomes invalid:
| Rule | Correct | Wrong |
|---|---|---|
| Keys must be in double quotes | "name": "John" |
name: "John" |
| Strings must use double quotes | "city": "Paris" |
"city": 'Paris' |
| No trailing commas | {"a": 1, "b": 2} |
{"a": 1, "b": 2,} |
| No comments allowed | {"a": 1} |
{"a": 1} // comment |
5. JSON Data Types
JSON supports exactly six data types:
String
Text in double quotes
"Hello World"
Number
Integer or decimal (no quotes)
42 or 3.14
Boolean
True or false (lowercase, no quotes)
true or false
Null
Empty or unknown value
null
Object
Collection of key-value pairs
{"key": "value"}
Array
Ordered list of values
[1, 2, 3]
Example with All Data Types
{
"name": "Alice", // String
"age": 28, // Number
"isStudent": false, // Boolean
"middleName": null, // Null
"address": { // Object
"city": "Boston",
"zip": "02101"
},
"hobbies": ["reading", "gaming"] // Array
}
Note: Comments shown above are for explanation onlyβreal JSON cannot have comments.
6. JSON Objects
A JSON object is a collection of key-value pairs enclosed in curly braces { }.
{
"firstName": "Emma",
"lastName": "Wilson",
"email": "emma@example.com"
}
Accessing Object Values
In JavaScript, you can access values using dot notation or bracket notation:
// If person contains the JSON above:
person.firstName // "Emma"
person["lastName"] // "Wilson"
7. JSON Arrays
Arrays are ordered lists of values enclosed in square brackets [ ].
Array of Strings
["apple", "banana", "cherry"]
Array of Numbers
[10, 20, 30, 40, 50]
Array of Objects
This is very commonβa list of similar items:
[
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 35}
]
Accessing Array Values
Arrays use zero-based indexing (first item is 0):
// If fruits = ["apple", "banana", "cherry"]
fruits[0] // "apple"
fruits[1] // "banana"
fruits[2] // "cherry"
8. Nested JSON
Real-world JSON often has objects inside objects, or arrays inside objects. This is called nesting.
Example: User Profile
{
"user": {
"id": 1001,
"name": "Sarah Johnson",
"contact": {
"email": "sarah@example.com",
"phone": "555-0123"
},
"orders": [
{"orderId": "A100", "total": 59.99},
{"orderId": "A101", "total": 124.50}
]
}
}
Accessing Nested Data
data.user.name // "Sarah Johnson"
data.user.contact.email // "sarah@example.com"
data.user.orders[0].total // 59.99
data.user.orders[1].orderId // "A101"
9. Using JSON in JavaScript
JavaScript provides two essential methods for working with JSON:
JSON.parse() - Convert JSON String to Object
When you receive JSON data (from a server, file, etc.), it comes as a string. Use parse() to convert it to a usable object:
// JSON string (received from server)
const jsonString = '{"name": "John", "age": 30}';
// Convert to JavaScript object
const user = JSON.parse(jsonString);
// Now you can use it
console.log(user.name); // "John"
console.log(user.age); // 30
JSON.stringify() - Convert Object to JSON String
When you need to send data (to a server, save to file, etc.), convert your object to a JSON string:
// JavaScript object
const product = {
name: "Laptop",
price: 999,
inStock: true
};
// Convert to JSON string
const jsonString = JSON.stringify(product);
console.log(jsonString);
// '{"name":"Laptop","price":999,"inStock":true}'
Pretty Printing JSON
Add spacing for readable output:
JSON.stringify(product, null, 2);
// Output:
// {
// "name": "Laptop",
// "price": 999,
// "inStock": true
// }
Fetching JSON from a Server
// Modern approach using fetch
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => {
console.log(data); // JSON is already parsed!
});
// Or with async/await
async function getUsers() {
const response = await fetch('https://api.example.com/users');
const users = await response.json();
console.log(users);
}
10. Common Mistakes to Avoid
{'name': 'John'} // β Wrong
{"name": "John"} // β
Correct
{
"a": 1,
"b": 2, // β Trailing comma after last item
}
{
"a": 1,
"b": 2 // β
No comma after last item
}
{name: "John"} // β Key without quotes
{"name": "John"} // β
Key in double quotes
{
"name": "John" // This is a comment β
}
{
"name": "John",
"_comment": "Use a field if you need notes" // β
Workaround
}
Or use JSONC (JSON with Comments) during development, then convert to JSON.
{"value": undefined} // β undefined doesn't exist in JSON
{"value": null} // β
Use null instead
11. Practice Exercises
Try these exercises to test your understanding:
Create JSON for a product with: name, price, category, and inStock status.
Show Solution
{
"name": "Wireless Mouse",
"price": 29.99,
"category": "Electronics",
"inStock": true
}
Create JSON for a shopping list with 3 items, each having name and quantity.
Show Solution
{
"shoppingList": [
{"name": "Milk", "quantity": 2},
{"name": "Bread", "quantity": 1},
{"name": "Eggs", "quantity": 12}
]
}
This JSON has 3 errors. Can you find them?
{
'username': "admin",
"email": 'admin@example.com',
"active": True,
}
Show Solution
Errors:
'username'- Single quotes on key (should be double quotes)'admin@example.com'- Single quotes on string valueTrue- Capital T (should be lowercasetrue)- Trailing comma after the last property
Corrected JSON:
{
"username": "admin",
"email": "admin@example.com",
"active": true
}
What's Next?
Now that you understand JSON basics, explore these topics: