A beginner's guide to JSON

Complete guide to JSON syntax, data types, and practical examples with tips for clean, reliable JSON. Learn how to work with JSON effectively.

• By Khashayar Azadpour

What is JSON?

JavaScript Object Notation (JSON) is a lightweight, text-based data format that has become the de facto standard for data exchange on the web. Created by Douglas Crockford in the early 2000s, JSON was designed to be both human-readable and machine-parseable, making it ideal for transmitting structured data between a server and a web application.

Today, JSON is everywhere—from REST APIs and configuration files to NoSQL databases and log files. Its simplicity and flexibility have made it the preferred choice for developers across virtually every programming language and platform.

Why JSON Matters

Understanding JSON is essential for modern web development and software engineering. Here’s why:

Core Syntax Rules

JSON syntax is strict and follows specific rules. Understanding these rules will help you avoid common parsing errors:

Data Types

JSON supports six fundamental data types:

  1. String: Text enclosed in double quotes
  2. Number: Integer or floating-point values (no quotes)
  3. Boolean: true or false (lowercase, no quotes)
  4. Null: Represents empty or non-existent values
  5. Array: Ordered list of values enclosed in square brackets
  6. Object: Unordered collection of key-value pairs enclosed in curly braces

Objects

Objects are collections of key-value pairs where keys must be strings in double quotes, and values can be any JSON data type:

{
  "name": "Sara Martinez",
  "age": 29,
  "email": "sara@example.com",
  "isActive": true,
  "department": null
}

Arrays

Arrays are ordered lists of values that can contain any JSON data type, including mixed types:

{
  "hobbies": ["reading", "running", "photography"],
  "scores": [95, 87, 92, 88],
  "mixedArray": ["text", 42, true, null, {"nested": "object"}]
}

Nested Structures

JSON’s real power comes from nesting objects and arrays to create complex data structures:

{
  "user": {
    "name": "Sara Martinez",
    "age": 29,
    "address": {
      "street": "123 Main St",
      "city": "Paris",
      "zip": "75000",
      "country": "France"
    },
    "contacts": [
      {
        "type": "email",
        "value": "sara@example.com",
        "primary": true
      },
      {
        "type": "phone",
        "value": "+33 1 23 45 67 89",
        "primary": false
      }
    ]
  }
}

Common Use Cases

API Responses

When you make an HTTP request to a REST API, the response typically comes back as JSON:

{
  "status": "success",
  "data": {
    "id": 12345,
    "username": "sara_dev",
    "created": "2025-01-15T10:30:00Z",
    "profile": {
      "bio": "Full-stack developer",
      "location": "Paris",
      "website": "https://saradev.com"
    }
  },
  "meta": {
    "timestamp": "2025-10-15T14:22:30Z",
    "version": "1.0"
  }
}

Configuration Files

Many modern tools use JSON for configuration. Here’s an example package.json structure:

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "A sample project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "jest",
    "build": "webpack --mode production"
  },
  "dependencies": {
    "express": "^4.18.0",
    "lodash": "^4.17.21"
  },
  "devDependencies": {
    "jest": "^29.0.0",
    "webpack": "^5.75.0"
  }
}

Data Exchange

JSON is perfect for transferring data between systems. For example, exporting user data:

{
  "export": {
    "date": "2025-10-15",
    "format": "JSON",
    "users": [
      {
        "id": 1,
        "name": "Alice Johnson",
        "email": "alice@example.com",
        "registeredDate": "2024-03-15"
      },
      {
        "id": 2,
        "name": "Bob Smith",
        "email": "bob@example.com",
        "registeredDate": "2024-05-20"
      }
    ],
    "totalCount": 2
  }
}

Best Practices

1. Consistent Naming Conventions

Choose a naming convention and stick with it throughout your JSON:

camelCase (most common in JavaScript):

{
  "firstName": "Sara",
  "lastName": "Martinez",
  "phoneNumber": "+33123456789"
}

snake_case (common in Python/Ruby):

{
  "first_name": "Sara",
  "last_name": "Martinez",
  "phone_number": "+33123456789"
}

2. Use Meaningful Key Names

Keys should be descriptive and self-explanatory:

Bad:

{
  "n": "Sara",
  "a": 29,
  "d": "2025-01-15"
}

Good:

{
  "name": "Sara",
  "age": 29,
  "registrationDate": "2025-01-15"
}

3. Maintain Predictable Structure

Objects of the same type should have consistent structures:

Bad (inconsistent):

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

Good (consistent):

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

4. Use ISO 8601 for Dates

Always use ISO 8601 format for dates and timestamps:

{
  "created": "2025-10-15T14:30:00Z",
  "lastModified": "2025-10-15T16:45:30.123Z",
  "dateOnly": "2025-10-15"
}

5. Handle Large Numbers Carefully

JavaScript’s JSON parser can lose precision with very large integers. For values that require exact precision (like IDs or currency), consider using strings:

{
  "userId": "9007199254740992",
  "transactionId": "1234567890123456789",
  "amount": "99.99"
}

Common Pitfalls and How to Avoid Them

Trailing Commas

JSON does not allow trailing commas. This is valid JavaScript but invalid JSON:

Invalid:

{
  "name": "Sara",
  "age": 29,
}

Valid:

{
  "name": "Sara",
  "age": 29
}

Single Quotes

JSON requires double quotes. Single quotes are not allowed:

Invalid:

{
  'name': 'Sara',
  'age': 29
}

Valid:

{
  "name": "Sara",
  "age": 29
}

Comments

Standard JSON does not support comments. If you need comments, consider using JSON5 or JSONC, or document your schema separately:

Invalid:

{
  // This is a user object
  "name": "Sara",
  "age": 29 /* current age */
}

Undefined Values

JSON doesn’t have an undefined type. Use null instead or omit the key entirely:

Invalid:

{
  "name": "Sara",
  "middleName": undefined
}

Valid Options:

{
  "name": "Sara",
  "middleName": null
}

or

{
  "name": "Sara"
}

Unquoted Keys

All keys must be strings in double quotes:

Invalid:

{
  name: "Sara",
  age: 29
}

Valid:

{
  "name": "Sara",
  "age": 29
}

Validating and Formatting JSON

Using Object Formatter

The easiest way to validate and format JSON is to use our Object Formatter tool:

  1. Paste your JSON into the input area
  2. The tool will automatically detect syntax errors
  3. View the formatted, beautified output
  4. Explore the structure with collapsible trees
  5. Copy the formatted JSON back to your code

Command Line Tools

You can also use command-line tools to validate JSON:

Using jq (Linux/Mac):

echo '{"name":"Sara","age":29}' | jq '.'

Using Python:

python -m json.tool input.json

Using Node.js:

node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('input.json')), null, 2))"

Working with JSON in Code

JavaScript

// Parse JSON string to object
const jsonString = '{"name":"Sara","age":29}';
const user = JSON.parse(jsonString);
console.log(user.name); // "Sara"

// Convert object to JSON string
const obj = { name: "Sara", age: 29 };
const json = JSON.stringify(obj);
console.log(json); // '{"name":"Sara","age":29}'

// Pretty print with indentation
const prettyJson = JSON.stringify(obj, null, 2);

Python

import json

# Parse JSON string to dict
json_string = '{"name":"Sara","age":29}'
user = json.loads(json_string)
print(user['name'])  # "Sara"

# Convert dict to JSON string
obj = {"name": "Sara", "age": 29}
json_str = json.dumps(obj)
print(json_str)  # '{"name": "Sara", "age": 29}'

# Pretty print with indentation
pretty_json = json.dumps(obj, indent=2)

Error Handling

Always wrap JSON parsing in try-catch blocks to handle invalid JSON gracefully:

try {
  const data = JSON.parse(userInput);
  // Process data...
} catch (error) {
  console.error('Invalid JSON:', error.message);
  // Handle error...
}

Advanced Topics

JSON Schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It’s useful for:

Example schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "email": {
      "type": "string",
      "format": "email"
    }
  },
  "required": ["name", "email"]
}

JSON vs. JavaScript Objects

While JSON syntax is derived from JavaScript object literals, they’re not identical:

FeatureJavaScript ObjectJSON
KeysCan be unquotedMust be quoted
QuotesSingle or doubleDouble only
Trailing commasAllowedNot allowed
CommentsAllowedNot allowed
FunctionsAllowedNot allowed
undefinedValid valueNot valid
Date objectsValidMust be strings

Next Steps

Now that you understand JSON fundamentals, here’s what to explore next:

  1. Practice with Real Data: Use our JSON formatter tool to paste, parse, and explore real JSON from APIs
  2. Learn JSON Schema: Validate your JSON structures with schemas
  3. Compare Formats: Read our article on JSON vs. YAML vs. XML to understand when to use each format
  4. Advanced Techniques: Explore our guide on Advanced YAML techniques

Summary

JSON is a simple yet powerful data format that’s essential for modern software development. Remember these key points:

With these fundamentals, you’re ready to work confidently with JSON in your projects. Practice with real-world examples using our Tools section, and you’ll quickly become proficient at reading, writing, and debugging JSON data structures.

Was this helpful?