[Avg. reading time: 8 minutes]
JSON
JSON (JavaScript Object Notation) is a lightweight, text-based data format that’s easy to read for both humans and machines. It was derived from JavaScript but is now language-independent, making it one of the most popular formats for data exchange between applications. Key Concepts:
What is JSON Used For?
- Storing configuration settings
- Exchanging data between web servers and browsers
- APIs (Application Programming Interfaces)
- Storing structured data in files or databases
- Mobile app data storage
JSON Data Types:
Strings: Text wrapped in double quotes
{"name": "Rachel Green"}
Numbers: Integer or floating-point
{"age": 27, "height": 5.5}
Booleans: true or false
{"isStudent": true}
null: Represents no value
{"middleName": null}
Arrays: Ordered lists of values
{
"hobbies": ["shopping", "singing", "swimming"]
}
Objects: Collections of key-value pairs
{
"address": {
"street": "123 Main St",
"city": "NYC",
"zipCode": "10001"
}
}
Important Rules:
- All property names must be in double quotes
- Values can be strings, numbers, objects, arrays, booleans, or null
- Commas separate elements in arrays and properties in objects
- No trailing commas allowed
- No comments allowed in JSON
- Must use UTF-8 encoding
Example
{
"studentInfo": {
"firstName": "Monica",
"lastName": "Geller",
"age": 22,
"isEnrolled": true,
"courses": [
{
"name": "Web Development",
"code": "CS101",
"grade": 95.5
},
{
"name": "Database Design",
"code": "CS102",
"grade": 88.0
}
],
"contact": {
"email": "monica.g@friends.com",
"phone": null,
"address": {
"street": "456 College Ave",
"city": "Columbia",
"state": "NY",
"zipCode": "13357"
}
}
}
}
Dont’s with JSON
- Using single quotes instead of double quotes
- Not enclosing property names in quotes
- Adding trailing commas
- Missing closing brackets or braces
- Using undefined or functions (not allowed in JSON)
- Adding comments (not supported in JSON)
Best Practices
- Always validate JSON using a JSON validator tool
- Pay attention to proper nesting of objects and arrays
- Ensure all opening brackets/braces have matching closing ones
- Check for proper use of commas
camelCase (e.g., firstName):
- Most popular in JavaScript/JSON
- Easy to read and type
- Matches JavaScript convention
Example:
{
"firstName": "John",
"lastLoginDate": "2024-12-20",
"phoneNumber": "555-0123"
}
snake_case (underscores, e.g., first_name):
- Popular in Python and SQL
- Very readable
- Clear word separation
Example:
{
"first_name": "John",
"last_login_date": "2024-12-20",
"phone_number": "555-0123"
}
kebab-case (hyphens, e.g., first-name):
- Common in URLs and HTML attributes
- NOT recommended for JSON
- Can cause issues because hyphen is also the subtraction operator
- Requires bracket notation to access in JavaScript
Example of why it’s problematic:
// This won't work
data.first-name // JavaScript interprets as data.first minus name
// Must use bracket notation
data["first-name"] // Works but less convenient