keecode logokeecode
Beginner
what is json
json explained
json tutorial
json format
json vs xml
javascript object notation

What is JSON? A Beginner's Guide to JavaScript Object Notation

Learn what JSON is, how it works, and why it's the standard for data exchange on the web. Beginner-friendly guide with examples and comparisons to XML.

Updated January 15, 2025

JSON (JavaScript Object Notation) is the most popular data format for exchanging information between web applications. This beginner-friendly guide explains what JSON is, how it works, and why it's everywhere.

Table of Contents

  1. What is JSON?
  2. JSON Syntax and Rules
  3. JSON Data Types
  4. Working with JSON
  5. JSON vs XML
  6. Common JSON Use Cases
  7. JSON Best Practices

What is JSON?

JSON stands for JavaScript Object Notation. It's a lightweight, text-based format for storing and transporting data.

Easy to Read: Looks like plain text
Easy to Write: Simple syntax
Lightweight: Minimal formatting = faster transfers
Language-Independent: Works with any programming language
Native JavaScript Support: Parse with one line of code
Widely Supported: Every API uses it

Real-World Analogy

Think of JSON like a shipping label on a package:

Package Label (JSON):
{
  "sender": "John Doe",
  "recipient": "Jane Smith",
  "address": "123 Main St",
  "contents": ["book", "pen", "notebook"],
  "weight": 2.5,
  "fragile": true
}

Easy to read ✅
Organized ✅
Standard format ✅
Anyone can understand it ✅

A Simple JSON Example

{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com",
  "isActive": true
}

This JSON represents a person with:

JSON Syntax and Rules

JSON has strict rules that make it consistent and easy to parse.

Basic Structure

JSON is built on two structures:

1. Objects: Collections of key-value pairs

{
  "key": "value",
  "anotherKey": "anotherValue"
}

2. Arrays: Ordered lists of values

[
  "value1",
  "value2",
  "value3"
]

The Golden Rules

{
  // 1. Keys MUST be in double quotes
  "name": "John",         // ✅ Correct
  'name': 'John',         // ❌ Wrong - single quotes not allowed
  name: "John",           // ❌ Wrong - keys need quotes

  // 2. Strings MUST use double quotes
  "city": "New York",     // ✅ Correct
  "city": 'New York',     // ❌ Wrong - single quotes not allowed

  // 3. No trailing commas
  "age": 30,
  "email": "john@example.com"  // ✅ No comma after last item
  // "city": "NYC",            // ❌ Wrong - trailing comma

  // 4. No comments allowed in JSON (these are just for explanation)

  // 5. Numbers don't need quotes
  "age": 30,              // ✅ Correct - number
  "age": "30",            // ❌ Wrong - this is a string now

  // 6. Booleans are lowercase
  "isActive": true,       // ✅ Correct
  "isActive": True,       // ❌ Wrong - must be lowercase

  // 7. Use null for empty values
  "middleName": null      // ✅ Correct
}

Valid JSON vs Invalid JSON

// ✅ VALID JSON
{
  "name": "John Doe",
  "age": 30,
  "hobbies": ["reading", "gaming"],
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

// ❌ INVALID JSON - Multiple errors
{
  name: 'John Doe',        // Missing quotes on key, using single quotes
  age: 30,
  hobbies: ["reading", "gaming"],  // Trailing comma
  address: {
    city: "New York",
    zip: "10001",          // Trailing comma
  },                       // Trailing comma
}

// ❌ INVALID JSON - Comments not allowed
{
  "name": "John Doe",  // This comment breaks JSON
  "age": 30
}

JSON Data Types

JSON supports six data types:

1. Strings

Text wrapped in double quotes.

{
  "name": "John Doe",
  "email": "john@example.com",
  "bio": "Software developer from NYC",
  "empty": ""
}

Special characters must be escaped:

{
  "quote": "He said \\"Hello\\"",
  "path": "C:\\\\Users\\\\John",
  "newline": "Line 1\\nLine 2",
  "tab": "Column1\\tColumn2"
}

2. Numbers

Integers or decimals (no quotes).

{
  "age": 30,
  "price": 19.99,
  "temperature": -5.5,
  "scientific": 1.5e10,
  "zero": 0
}

3. Booleans

True or false (lowercase, no quotes).

{
  "isActive": true,
  "isDeleted": false,
  "hasAccess": true
}

4. Null

Represents no value or empty (lowercase, no quotes).

{
  "middleName": null,
  "profilePicture": null,
  "deletedAt": null
}

5. Objects

Collections of key-value pairs wrapped in { }.

{
  "user": {
    "name": "John Doe",
    "email": "john@example.com",
    "address": {
      "street": "123 Main St",
      "city": "New York",
      "country": "USA"
    }
  }
}

6. Arrays

Ordered lists wrapped in [ ].

{
  "numbers": [1, 2, 3, 4, 5],
  "names": ["Alice", "Bob", "Charlie"],
  "mixed": [1, "two", true, null],
  "users": [
    {
      "id": 1,
      "name": "Alice"
    },
    {
      "id": 2,
      "name": "Bob"
    }
  ],
  "empty": []
}

Complex Example

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "age": 30,
  "isActive": true,
  "roles": ["admin", "editor"],
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zip": "10001",
    "coordinates": {
      "lat": 40.7128,
      "lng": -74.0060
    }
  },
  "orders": [
    {
      "id": 1001,
      "date": "2025-01-10",
      "total": 99.99,
      "items": [
        { "name": "Book", "price": 29.99 },
        { "name": "Pen", "price": 5.00 }
      ]
    }
  ],
  "preferences": {
    "notifications": true,
    "theme": "dark",
    "language": "en"
  },
  "lastLogin": "2025-01-15T10:30:00Z",
  "profilePicture": null
}

Working with JSON

JavaScript: Parse and Stringify

// JSON string (what you get from APIs)
const jsonString = '{"name":"John","age":30}';

// 1. PARSE - Convert JSON string to JavaScript object
const obj = JSON.parse(jsonString);
console.log(obj.name);  // "John"
console.log(obj.age);   // 30

// 2. STRINGIFY - Convert JavaScript object to JSON string
const user = {
  name: 'Jane',
  age: 25
};
const json = JSON.stringify(user);
console.log(json);  // '{"name":"Jane","age":25}'

// Pretty print with indentation
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
// {
//   "name": "Jane",
//   "age": 25
// }

Fetching JSON from API

// Fetch data from API (returns JSON)
fetch('https://api.example.com/users/123')
  .then(response => response.json())  // Parse JSON automatically
  .then(user => {
    console.log(user.name);
    console.log(user.email);
  });

// Async/await version
async function getUser() {
  const response = await fetch('https://api.example.com/users/123');
  const user = await response.json();
  console.log(user);
}

Sending JSON to API

// Send JSON data to server
const newUser = {
  name: 'John Doe',
  email: 'john@example.com',
  age: 30
};

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'  // Important!
  },
  body: JSON.stringify(newUser)  // Convert object to JSON string
})
.then(response => response.json())
.then(data => console.log('Created:', data));

Python: Working with JSON

import json

# Parse JSON string
json_string = '{"name": "John", "age": 30}'
user = json.loads(json_string)
print(user['name'])  # John

# Convert dict to JSON
user = {
    'name': 'Jane',
    'age': 25
}
json_string = json.dumps(user)
print(json_string)  # {"name": "Jane", "age": 25}

# Pretty print
pretty_json = json.dumps(user, indent=2)
print(pretty_json)

# Read from file
with open('data.json', 'r') as file:
    data = json.load(file)

# Write to file
with open('data.json', 'w') as file:
    json.dump(user, file, indent=2)

PHP: Working with JSON

<?php
// Parse JSON string
$jsonString = '{"name":"John","age":30}';
$user = json_decode($jsonString);
echo $user->name;  // John

// Convert array to JSON
$user = [
    'name' => 'Jane',
    'age' => 25
];
$json = json_encode($user);
echo $json;  // {"name":"Jane","age":25}

// Pretty print
$prettyJson = json_encode($user, JSON_PRETTY_PRINT);
echo $prettyJson;
?>

JSON vs XML

Both JSON and XML are used for data exchange, but JSON has become the standard.

Same Data in JSON vs XML

// JSON (concise and readable)
{
  "user": {
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com",
    "roles": ["admin", "editor"]
  }
}
<!-- XML (verbose) -->
<user>
  <id>123</id>
  <name>John Doe</name>
  <email>john@example.com</email>
  <roles>
    <role>admin</role>
    <role>editor</role>
  </roles>
</user>

Comparison Table

featurejsonxml
Readability✅ Very easy🟡 Moderate
File Size✅ Smaller❌ Larger
Parsing Speed✅ Faster❌ Slower
Native JS Support✅ Built-in❌ Requires parser
Arrays✅ Native🟡 Workaround needed
Attributes❌ Not supported✅ Supported
Comments❌ Not allowed✅ Allowed
Data Types✅ Numbers, booleans, null❌ Everything is text

When to Use Each

Use JSON (99% of cases):
✅ Web APIs
✅ Mobile apps
✅ Modern applications
✅ When speed matters
✅ When simplicity matters

Use XML (rare cases):
✅ Legacy systems
✅ SOAP web services
✅ Complex documents with metadata
✅ When attributes are needed
✅ RSS/Atom feeds

Common JSON Use Cases

1. API Responses

// Request
GET https://api.example.com/users/123

// Response
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "status": "active"
}

2. Configuration Files

// package.json (Node.js projects)
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "test": "jest"
  },
  "dependencies": {
    "express": "^4.18.0"
  }
}

3. Storing Data

// users.json
[
  {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
  },
  {
    "id": 2,
    "name": "Bob",
    "email": "bob@example.com"
  }
]

4. Form Data

// Sending form data as JSON
const formData = {
  name: document.getElementById('name').value,
  email: document.getElementById('email').value,
  message: document.getElementById('message').value
};

fetch('/api/contact', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(formData)
});

5. LocalStorage

// Save to localStorage
const user = {
  name: 'John',
  preferences: { theme: 'dark' }
};
localStorage.setItem('user', JSON.stringify(user));

// Retrieve from localStorage
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.name);  // "John"

JSON Best Practices

1. Use Consistent Naming

// ✅ GOOD - camelCase (most common)
{
  "firstName": "John",
  "lastName": "Doe",
  "emailAddress": "john@example.com"
}

// ✅ GOOD - snake_case (alternative)
{
  "first_name": "John",
  "last_name": "Doe",
  "email_address": "john@example.com"
}

// ❌ BAD - Inconsistent
{
  "firstName": "John",
  "last_name": "Doe",
  "Email-Address": "john@example.com"
}

2. Keep JSON Flat When Possible

// ✅ GOOD - Simple and flat
{
  "userId": 123,
  "userName": "John",
  "userEmail": "john@example.com"
}

// 🟡 OKAY - Nested when it makes sense
{
  "user": {
    "id": 123,
    "name": "John",
    "email": "john@example.com"
  }
}

// ❌ BAD - Unnecessarily nested
{
  "data": {
    "user": {
      "profile": {
        "personal": {
          "name": "John"
        }
      }
    }
  }
}

3. Use Arrays for Lists

// ✅ GOOD - Array of objects
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ]
}

// ❌ BAD - Numbered keys
{
  "user1": { "id": 1, "name": "Alice" },
  "user2": { "id": 2, "name": "Bob" }
}

4. Include Metadata

// ✅ GOOD - With useful metadata
{
  "data": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 100
  },
  "timestamp": "2025-01-15T10:30:00Z"
}

5. Handle Errors Gracefully

// Always wrap JSON parsing in try-catch
try {
  const data = JSON.parse(jsonString);
  console.log(data);
} catch (error) {
  console.error('Invalid JSON:', error);
  // Handle error gracefully
}

6. Validate JSON

// Check if string is valid JSON
function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}

console.log(isValidJSON('{"name":"John"}'));  // true
console.log(isValidJSON('{name:"John"}'));    // false

Common JSON Errors

Error 1: Trailing Commas

// ❌ ERROR: Unexpected token } in JSON
{
  "name": "John",
  "age": 30,  ← Remove this comma
}

// ✅ FIXED
{
  "name": "John",
  "age": 30
}

Error 2: Single Quotes

// ❌ ERROR: Unexpected token ' in JSON
{
  'name': 'John'
}

// ✅ FIXED: Use double quotes
{
  "name": "John"
}

Error 3: Unquoted Keys

// ❌ ERROR: Unexpected token n in JSON
{
  name: "John"
}

// ✅ FIXED: Quote the keys
{
  "name": "John"
}

Summary

JSON is the universal format for data exchange on the web. Its simplicity, readability, and widespread support make it the go-to choice for APIs, configuration files, and data storage.

Key Takeaways:

✅ JSON = JavaScript Object Notation
✅ Uses key-value pairs and arrays
✅ Six data types: string, number, boolean, null, object, array
✅ Strict syntax: double quotes, no trailing commas, no comments
✅ Use JSON.parse() to read, JSON.stringify() to write
✅ Simpler and faster than XML
✅ Standard format for web APIs
✅ Supported by every programming language