---
title: "JSON"
description: "JSON (JavaScript Object Notation) is a lightweight, text-based data format used for data exchange. It supports objects, arrays, strings, numbers, booleans, and null values, making it universal across all programming languages."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/json
---

# JSON

JSON (JavaScript Object Notation) is a lightweight, text-based data exchange format. It's universally supported across programming languages and provides a simple, readable way to structure and transmit data.

Browse the sections below to explore JSON syntax, data types, and practical examples.

## Getting Started

Fundamental JSON concepts and syntax for beginners.

### Basic Structure

Understanding JSON file structure and format.

**Keywords:** structure, JSON, format, syntax, valid

#### Minimal JSON object

```json
{}
```

_exec_
```bash
echo '{}' | jq .
```

_output_
```json
{}
```

The simplest valid JSON structure is an empty object.

- JSON must contain valid data structure (object or array at root).
- An empty object {} is a valid JSON document.

#### Valid JSON structure

```json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
```

_exec_
```bash
echo '{"name":"John","age":30,"city":"New York"}' | jq .
```

_output_
```json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
```

A basic JSON object with key-value pairs representing a person.

- Keys must be strings enclosed in double quotes.
- Values can be strings, numbers, booleans, null, objects, or arrays.

#### JSON file format

```json
{
  "version": "1.0",
  "author": "Admin",
  "timestamp": "2025-02-28"
}
```

_exec_
```bash
cat config.json | jq .
```

_output_
```json
{
  "version": "1.0",
  "author": "Admin",
  "timestamp": "2025-02-28"
}
```

A typical JSON file structure for configuration data.

- JSON files should be saved with .json extension.
- Files should contain valid JSON starting with { or [.

**Best practices:**

- Always use double quotes for keys and string values.
- Validate JSON structure before deployment.
- Use UTF-8 encoding for JSON files.

**Common errors:**

- **Single quotes instead of double quotes**: JSON requires double quotes. Use "key" not 'key'.
- **Trailing comma after last element**: Remove comma after final item in objects or arrays.

### Data Types

JSON data types and their usage.

**Keywords:** data types, JSON, objects, arrays, strings, numbers, boolean, 

#### All JSON data types

```json
{
  "string": "Hello",
  "number": 42,
  "decimal": 3.14,
  "boolean_true": true,
  "boolean_false": false,
  "null_value": null,
  "array": [1, 2, 3],
  "object": {"key": "value"}
}
```

_exec_
```bash
jq . data.json
```

_output_
```json
{
  "string": "Hello",
  "number": 42,
  "decimal": 3.14,
  "boolean_true": true,
  "boolean_false": false,
  "null_value": null,
  "array": [1, 2, 3],
  "object": {"key": "value"}
}
```

Demonstrates all seven JSON data types.

- JSON has exactly seven data types.
- Booleans are lowercase true and false (not True/False).

#### Type examples

```json
{
  "user": {
    "id": 123,
    "active": true,
    "score": 98.5,
    "notes": null,
    "tags": ["admin", "verified"]
  }
}
```

_exec_
```bash
jq '.user' user.json
```

_output_
```json
{
  "id": 123,
  "active": true,
  "score": 98.5,
  "notes": null,
  "tags": ["admin", "verified"]
}
```

Real-world example showing mixed data types in a user object.

- Use null to represent missing or undefined values.
- Numbers don't need quotes.

#### Multiple types in array

```json
{
  "mixed": [
    "string",
    42,
    true,
    null,
    {"nested": "object"},
    [1, 2, 3]
  ]
}
```

_exec_
```bash
jq '.mixed | length' mixed.json
```

_output_
```bash
6
```

Arrays can contain any combination of JSON data types.

- Arrays maintain order and can mix different types.
- Be cautious with mixed-type arrays - harder to parse.

**Best practices:**

- Use appropriate types for each value.
- Use null instead of empty strings for missing values.
- Keep type consistency within arrays when possible.

**Common errors:**

- **Using undefined or NaN**: JSON doesn't support undefined. Use null instead.
- **Unquoted booleans**: Use true/false (lowercase), not TRUE/False.

### Whitespace and Comments

Handling whitespace, formatting, and comments in JSON.

**Keywords:** whitespace, formatting, comments, indentation, pretty-print

#### Formatted JSON

```json
{
  "name": "Alice",
  "age": 28,
  "email": "alice@example.com"
}
```

_exec_
```bash
jq . user.json
```

_output_
```json
{
  "name": "Alice",
  "age": 28,
  "email": "alice@example.com"
}
```

Pretty-printed JSON with indentation for readability.

- Whitespace outside quotes is ignored in JSON.
- Use consistent indentation (typically 2 or 4 spaces).

#### Minified JSON

```json
{"name":"Bob","age":35,"email":"bob@example.com","active":true}
```

_exec_
```bash
jq -c . user.json
```

_output_
```bash
{"name":"Bob","age":35,"email":"bob@example.com","active":true}
```

Minified JSON removes all unnecessary whitespace for smaller file size.

- Minified JSON is harder to read but smaller for transmission.
- Both formatted and minified are equivalent.

#### Pretty-printed with indentation

```json
{
    "user": {
        "id": 1,
        "details": {
            "name": "Carol",
            "role": "admin"
        }
    }
}
```

_exec_
```bash
jq . --indent 4 config.json
```

_output_
```bash
4-space indentation applied
```

JSON with 4-space indentation standard.

- Most style guides recommend 2-4 spaces for indentation.
- Line breaks can appear within strings using escape sequences.

**Best practices:**

- Use consistent indentation for readability.
- Minify for production/transmission.
- Format for development and debugging.

**Common errors:**

- **Comments in JSON files**: JSON doesn't support comments. Use a separate file or documentation.
- **Inconsistent indentation**: Standardize indentation (2 or 4 spaces) across projects.

**Advanced notes:**

- **JSONC Format:** JSON with Comments (JSONC) extends JSON to allow comments - used in VS Code config files.
- **Standards:** RFC 7159 defines JSON format - whitespace is insignificant outside strings.

## Objects

Working with JSON objects and key-value pairs.

### Object Syntax

Understanding JSON object structure and syntax.

**Keywords:** objects, syntax, braces, key-value, pairs

#### Empty object

```json
{}
```

_exec_
```bash
echo '{}' | jq 'type'
```

_output_
```bash
"object"
```

An empty object contains no key-value pairs.

- Empty objects are valid and often used as defaults.
- Objects use curly braces {} as delimiters.

#### Simple object

```json
{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30
}
```

_exec_
```bash
jq . person.json
```

_output_
```json
{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30
}
```

A simple object with three key-value pairs.

- Each key is a string in double quotes.
- Key-value pairs are separated by colons.
- Pairs are separated by commas.

#### Nested object

```json
{
  "person": {
    "name": "Jane",
    "contact": {
      "email": "jane@example.com",
      "phone": "555-1234"
    }
  }
}
```

_exec_
```bash
jq '.person.contact' person.json
```

_output_
```json
{
  "email": "jane@example.com",
  "phone": "555-1234"
}
```

Objects can be nested within other objects.

- Objects can contain other objects as values.
- Nesting can go multiple levels deep.

**Best practices:**

- Use meaningful key names.
- Keep object structure shallow when possible.
- Use consistent naming conventions (camelCase or snake_case).

**Common errors:**

- **Unquoted keys**: All keys must be strings enclosed in double quotes.
- **Single quotes for keys**: JSON requires double quotes for keys.

### Object Keys

Understanding JSON object key naming and conventions.

**Keywords:** keys, naming, conventions, strings, identifiers

#### Simple key names

```json
{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com",
  "verified": true
}
```

_exec_
```bash
jq 'keys' user.json
```

_output_
```json
[
  "email",
  "id",
  "name",
  "verified"
]
```

Standard key names that follow common conventions.

- Use camelCase or snake_case consistently.
- Keep key names short and descriptive.

#### Keys with spaces

```json
{
  "first name": "John",
  "last name": "Smith",
  "home address": "123 Main St"
}
```

_exec_
```bash
jq '["first name"]' person.json
```

_output_
```bash
"John"
```

Keys can contain spaces if enclosed in double quotes.

- Keys with spaces are valid but harder to access programmatically.
- Use underscores or camelCase instead of spaces.

#### Keys with special characters

```json
{
  "@id": "obj-123",
  "$type": "Person",
  "api-key": "abc123xyz",
  "time&date": "2025-02-28"
}
```

_exec_
```bash
jq '.["@id"]' metadata.json
```

_output_
```bash
"obj-123"
```

Keys can contain special characters but must be quoted.

- Special characters require bracket notation to access.
- Avoid special characters in keys when possible.

**Best practices:**

- Use simple, descriptive key names.
- Follow consistent naming convention across project.
- Avoid spaces and special characters in keys.

**Common errors:**

- **Unquoted keys with hyphens**: Keys with hyphens must be quoted: "api-key".
- **Duplicate keys**: JSON allows duplicate keys - last value wins, but this is bad practice.

**Advanced notes:**

- **Key Ordering:** In JavaScript/Python, key order may not be guaranteed. Store order-critical data in arrays.

### Object Values

Understanding JSON object values and nesting.

**Keywords:** values, nesting, types, heterogeneous, homogeneous

#### Different value types

```json
{
  "stringValue": "text",
  "numberValue": 42,
  "decimalValue": 3.14,
  "booleanValue": true,
  "nullValue": null,
  "arrayValue": [1, 2, 3],
  "objectValue": {"nested": true}
}
```

_exec_
```bash
jq '.stringValue' data.json
```

_output_
```bash
"text"
```

Objects can contain any valid JSON value.

- Values can be of any JSON type.
- Use appropriate types for each value.

#### Nested objects as values

```json
{
  "user": {
    "profile": {
      "name": "Bob",
      "age": 35
    },
    "settings": {
      "notifications": true,
      "theme": "dark"
    }
  }
}
```

_exec_
```bash
jq '.user.settings' user.json
```

_output_
```json
{
  "notifications": true,
  "theme": "dark"
}
```

Objects can be deeply nested within each other.

- Nesting allows hierarchical data representation.
- Access nested values using dot notation.

#### Array values in objects

```json
{
  "user": "Carol",
  "hobbies": ["reading", "gaming", "cooking"],
  "scores": [95, 87, 92, 88],
  "contacts": [
    {"type": "email", "value": "carol@example.com"},
    {"type": "phone", "value": "555-5678"}
  ]
}
```

_exec_
```bash
jq '.hobbies[0]' user.json
```

_output_
```bash
"reading"
```

Objects can contain arrays as values.

- Arrays can be homogeneous (same type) or heterogeneous (mixed types).
- Access array elements by index notation.

**Best practices:**

- Use descriptive keys that indicate value type.
- Keep nesting levels reasonable (2-3 typically).
- Use arrays for collections, objects for properties.

**Common errors:**

- **Inconsistent value types for same key**: Keep consistent types across similar objects.
- **Excessively nested structures**: Consider flattening or restructuring data.

## Arrays

Working with JSON arrays and list structures.

### Array Syntax

Understanding JSON array structure and syntax.

**Keywords:** arrays, syntax, brackets, elements, lists

#### Empty array

```json
[]
```

_exec_
```bash
echo '[]' | jq 'type'
```

_output_
```bash
"array"
```

An empty array contains no elements.

- Empty arrays are valid and used as defaults.
- Arrays use square brackets [] as delimiters.

#### Simple array

```json
[
  "apple",
  "banana",
  "cherry"
]
```

_exec_
```bash
jq . fruits.json
```

_output_
```json
[
  "apple",
  "banana",
  "cherry"
]
```

A simple array of strings.

- Array elements are separated by commas.
- No trailing comma after last element.

#### Mixed types array

```json
[
  "string",
  42,
  true,
  null,
  {"key": "value"},
  [1, 2, 3]
]
```

_exec_
```bash
jq 'length' mixed.json
```

_output_
```bash
6
```

Arrays can contain heterogeneous types.

- Mixed-type arrays are valid but harder to parse.
- Prefer homogeneous arrays when possible.

**Best practices:**

- Keep arrays homogeneous when possible.
- Use descriptive key names for array containers.
- Array indices start at 0.

**Common errors:**

- **Trailing comma in array**: Remove comma after last element.
- **Accessing array with object notation**: Use index notation: array[0] not array.0.

### Array Elements

Understanding JSON array element types and access.

**Keywords:** elements, items, values, indexing, access

#### Array of objects

```json
[
  {
    "id": 1,
    "name": "Alice",
    "role": "admin"
  },
  {
    "id": 2,
    "name": "Bob",
    "role": "user"
  }
]
```

_exec_
```bash
jq '.[0].name' users.json
```

_output_
```bash
"Alice"
```

Array containing objects.

- Access elements by index and key: array[0].key.
- Perfect for representing collections of entities.

#### Nested arrays

```json
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
```

_exec_
```bash
jq '.[1][2]' matrix.json
```

_output_
```bash
6
```

Array of arrays (2D matrix structure).

- Access nested arrays: array[row][column].
- Useful for matrix or grid data.

#### Homogeneous array

```json
{
  "scores": [95, 87, 92, 88, 91],
  "temperatures": [72.5, 68.3, 75.1, 69.8]
}
```

_exec_
```bash
jq '.scores | length' data.json
```

_output_
```bash
5
```

Arrays with all elements of same type.

- Homogeneous arrays are easier to process.
- All elements should have consistent meaning.

**Best practices:**

- Use homogeneous arrays (all same type).
- Use arrays for ordered collections.
- Document array element structure.

**Common errors:**

- **Assuming specific element type**: Always check type before operations.
- **Index out of bounds**: Validate array length before accessing by index.

**Advanced notes:**

- **Array Iteration:** Most languages iterate arrays with loops or map functions.

### Array Operations

Common operations with JSON arrays.

**Keywords:** operations, indexing, iteration, length, access

#### Accessing array elements

```json
{
  "colors": [
    "red",
    "green",
    "blue",
    "yellow"
  ]
}
```

_exec_
```bash
jq '.colors[2]' colors.json
```

_output_
```bash
"blue"
```

Access array element by zero-based index.

- Index 0 is the first element.
- Negative indices work in some languages.

#### Array length

```json
{
  "items": ["apple", "banana", "cherry", "date"]
}
```

_exec_
```bash
jq '.items | length' items.json
```

_output_
```bash
4
```

Get the number of elements in an array.

- Length is commonly needed for iteration.
- Empty array has length 0.

#### Slicing arrays

```json
{
  "numbers": [10, 20, 30, 40, 50, 60]
}
```

_exec_
```bash
jq '.numbers[2:5]' numbers.json
```

_output_
```json
[
  30,
  40,
  50
]
```

Extract subset of array elements.

- Slice notation: array[start:end].
- End index is exclusive.

**Best practices:**

- Always check array length before access.
- Use appropriate iteration methods for your language.
- Filter and map arrays functionally.

**Common errors:**

- **Accessing undefined index**: Validate length or use default values.
- **Mutating during iteration**: Create new array or use filter/map methods.

## Strings and Numbers

Working with JSON strings and numeric values.

### String Format

Understanding JSON string format and syntax.

**Keywords:** strings, format, quotes, text, characters

#### Simple strings

```json
{
  "greeting": "Hello",
  "sentence": "This is a complete sentence.",
  "empty": ""
}
```

_exec_
```bash
jq '.greeting' strings.json
```

_output_
```bash
"Hello"
```

Basic string values enclosed in double quotes.

- Strings must use double quotes, not single quotes.
- Empty strings are valid values.

#### Escaped characters

```json
{
  "newline": "Line 1\nLine 2",
  "tab": "Column 1\tColumn 2",
  "quote": "She said \"Hello\"",
  "backslash": "C:\\Users\\Name"
}
```

_exec_
```bash
jq '.newline' strings.json
```

_output_
```bash
"Line 1
Line 2"
```

Strings with escape sequences for special characters.

- Escape sequences start with backslash.
- Common escapes: \n (newline), \t (tab), \" (quote).

#### Unicode strings

```json
{
  "emoji": "Hello 👋",
  "chinese": "你好",
  "unicode": "A\u0301"
}
```

_exec_
```bash
jq '.emoji' unicode.json
```

_output_
```bash
"Hello 👋"
```

Strings can contain Unicode characters and emojis.

- JSON supports full Unicode character set.
- Unicode escape: \uXXXX where XXXX is hex code.

**Best practices:**

- Use UTF-8 encoding for JSON files.
- Escape special characters properly.
- Keep string values reasonably sized.

**Common errors:**

- **Unescaped newline in string**: Use \n for newlines in JSON strings.
- **Single quotes for strings**: JSON requires double quotes for strings.

### String Escapes

Understanding JSON escape sequences.

**Keywords:** escapes, sequences, special characters, formatting, unicode

#### Common escape sequences

```json
{
  "quote": "He said \"Hello\"",
  "backslash": "Path: C:\\Users\\",
  "newline": "First\nSecond",
  "tab": "Col1\tCol2",
  "carriage_return": "Line1\rLine2"
}
```

_exec_
```bash
jq '.quote' escapes.json
```

_output_
```bash
"He said \"Hello\""
```

Common escape sequences in JSON strings.

- \" escapes double quote character.
- \\ escapes backslash itself.
- \n for newline, \t for tab.

#### All escape sequences

```json
{
  "quote": "\"",
  "backslash": "\\",
  "forward_slash": "/",
  "backspace": "\b",
  "form_feed": "\f",
  "newline": "\n",
  "carriage_return": "\r",
  "tab": "\t"
}
```

_exec_
```bash
jq 'keys' escapes.json
```

_output_
```json
[
  "backslash",
  "backspace",
  "carriage_return",
  "form_feed",
  "forward_slash",
  "newline",
  "quote",
  "tab"
]
```

All eight JSON escape sequences.

- \/ is optional (usually not needed).
- \b and \f are rarely used in practice.

#### Unicode escape sequences

```json
{
  "copyright": "\u00A9 2025",
  "greek": "\u03B1 (alpha)",
  "emoji_unicode": "\uD83D\uDC4B"
}
```

_exec_
```bash
jq '.copyright' unicode.json
```

_output_
```bash
"© 2025"
```

Unicode escape sequences using \uXXXX notation.

- Unicode specified as 4 hex digits after \u.
- Useful for non-ASCII characters.

**Best practices:**

- Use escape sequences where required by JSON spec.
- Prefer UTF-8 encoding for non-ASCII characters.
- Document strings with special characters.

**Common errors:**

- **Unescaped quote in string**: Use \" for quotes within strings.
- **Raw newline in string**: Use \n instead of literal newline.

**Advanced notes:**

- **JSON Safe Strings:** Some characters must be escaped to ensure JSON validity.

### Number Format

Understanding JSON number formatting.

**Keywords:** numbers, integers, decimals, scientific, notation

#### Integer numbers

```json
{
  "year": 2025,
  "count": 42,
  "negative": -100,
  "zero": 0,
  "large": 1000000
}
```

_exec_
```bash
jq '.year' numbers.json
```

_output_
```bash
2025
```

Integer values without decimal points.

- Integers are whole numbers.
- Can be positive, negative, or zero.

#### Decimal numbers

```json
{
  "pi": 3.14159,
  "price": 19.99,
  "temperature": -5.5,
  "percentage": 0.95
}
```

_exec_
```bash
jq '.pi' decimals.json
```

_output_
```bash
3.14159
```

Decimal (floating-point) numbers.

- Include decimal point and digits after it.
- Precision may vary by language.

#### Scientific notation

```json
{
  "avogadro": 6.02214076e+23,
  "tiny": 1.6e-19,
  "standard": 1.5e2
}
```

_exec_
```bash
jq '.avogadro' scientific.json
```

_output_
```bash
6.02214076e+23
```

Numbers in scientific notation.

- Use e or E for exponent notation.
- Useful for very large or very small numbers.

**Best practices:**

- Use appropriate precision for decimals.
- Document units for numeric values.
- Avoid floating-point precision issues in comparisons.

**Common errors:**

- **Numbers with leading zeros**: JSON doesn't allow leading zeros (except 0.x).
- **Quoted numbers**: Remove quotes from numeric values.

**Advanced notes:**

- **Precision Issues:** Floating-point numbers may have precision limits. Consider using strings for high-precision numbers.

## Complex Structures

Building complex JSON data structures.

### Nested Objects

Working with objects nested within other objects.

**Keywords:** nested, objects, hierarchy, deep, nesting

#### Two-level nesting

```json
{
  "person": {
    "name": "Alice",
    "age": 30
  }
}
```

_exec_
```bash
jq '.person.name' user.json
```

_output_
```bash
"Alice"
```

Basic nested object structure.

- Access nested values with dot notation.
- Each level is another object.

#### Multi-level nesting

```json
{
  "company": {
    "department": {
      "team": {
        "lead": "Bob",
        "size": 5
      }
    }
  }
}
```

_exec_
```bash
jq '.company.department.team.lead' org.json
```

_output_
```bash
"Bob"
```

Deep nesting of multiple object levels.

- Keep nesting depth reasonable (3-4 levels typical).
- Deep nesting becomes harder to navigate.

#### Complex hierarchy

```json
{
  "application": {
    "name": "MyApp",
    "version": "1.0",
    "config": {
      "database": {
        "host": "localhost",
        "port": 5432,
        "credentials": {
          "user": "admin",
          "password": "secret"
        }
      }
    }
  }
}
```

_exec_
```bash
jq '.application.config.database.host' config.json
```

_output_
```bash
"localhost"
```

Complex hierarchical configuration structure.

- Used for application configuration.
- Represents real-world nested data.

**Best practices:**

- Keep nesting depth to 2-3 levels when possible.
- Use descriptive names at each level.
- Consider flattening or restructuring if too deep.

**Common errors:**

- **Excessive nesting depth**: Refactor structure to be flatter.
- **Accessing non-existent nested properties**: Check structure and handle null/undefined.

**Advanced notes:**

- **Schema Validation:** Use JSON Schema to validate nested structure.

### Nested Arrays

Working with arrays nested within other structures.

**Keywords:** nested, arrays, collections, multi-dimensional, lists

#### Array of arrays

```json
{
  "matrix": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]
}
```

_exec_
```bash
jq '.matrix[1][2]' matrix.json
```

_output_
```bash
6
```

Two-dimensional array structure.

- Access with double bracket notation.
- Row column indices like [1][2].

#### Array of objects

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

_exec_
```bash
jq '.users[0].email' users.json
```

_output_
```bash
"alice@example.com"
```

Common structure for collections of entities.

- Perfect for API responses with multiple items.
- Each object is a separate item.

#### Complex nesting

```json
{
  "departments": [
    {
      "name": "Engineering",
      "members": [
        {"name": "Alice", "roles": ["dev", "lead"]},
        {"name": "Bob", "roles": ["dev", "devops"]}
      ]
    },
    {
      "name": "Sales",
      "members": [
        {"name": "Carol", "roles": ["sales"]}
      ]
    }
  ]
}
```

_exec_
```bash
jq '.departments[0].members[1].roles[0]' org.json
```

_output_
```bash
"dev"
```

Complex nested array and object combination.

- Represents real-world hierarchical data.
- Access with combined notation.

**Best practices:**

- Use arrays for collections, objects for properties.
- Keep nesting depth reasonable.
- Document the structure of nested arrays.

**Common errors:**

- **Treating array as object**: Use index notation for arrays, dot for objects.
- **Assuming all items are same structure**: Validate before accessing properties.

### Mixed Structures

Combining objects and arrays in real-world structures.

**Keywords:** mixed, structures, real-world, patterns, api

#### API response structure

```json
{
  "status": "success",
  "data": {
    "items": [
      {
        "id": 1,
        "title": "Item 1",
        "price": 29.99
      },
      {
        "id": 2,
        "title": "Item 2",
        "price": 39.99
      }
    ],
    "pagination": {
      "page": 1,
      "total": 50
    }
  }
}
```

_exec_
```bash
jq '.data.items[0].title' response.json
```

_output_
```bash
"Item 1"
```

Typical API response with status and nested data.

- Common pattern in REST APIs.
- Combines object and array nesting.

#### Configuration structure

```json
{
  "server": {
    "host": "localhost",
    "port": 3000,
    "endpoints": [
      {
        "path": "/api/users",
        "method": "GET"
      },
      {
        "path": "/api/users",
        "method": "POST"
      }
    ]
  }
}
```

_exec_
```bash
jq '.server.endpoints[1].path' config.json
```

_output_
```bash
"/api/users"
```

Configuration combining objects and array of objects.

- Used for application configuration.
- Organizes settings hierarchically.

#### Data model structure

```json
{
  "user": {
    "id": 123,
    "profile": {
      "firstName": "John",
      "lastName": "Doe",
      "avatar": "https://example.com/avatar.jpg"
    },
    "subscriptions": [
      {
        "plan": "premium",
        "renewalDate": "2025-03-28"
      }
    ],
    "preferences": {
      "notifications": true,
      "themes": ["dark", "light"]
    }
  }
}
```

_exec_
```bash
jq '.user.preferences.themes[0]' user.json
```

_output_
```bash
"dark"
```

Comprehensive data model with mixed nesting.

- Represents complete user profile.
- Combines all structure types.

**Best practices:**

- Use consistent structure for same data types.
- Document expected structure clearly.
- Validate structure on both sides of APIs.

**Common errors:**

- **Inconsistent structure across items**: Ensure all array items have same properties.
- **Over-nesting or over-flattening**: Balance between clarity and depth.

## Validation and Best Practices

Validating and properly formatting JSON data.

### Valid JSON

Valid JSON structure and common mistakes.

**Keywords:** validation, valid, invalid, syntax, errors

#### Valid JSON structure

```json
{
  "name": "John",
  "age": 30,
  "email": "john@example.com",
  "active": true,
  "roles": ["admin", "user"],
  "metadata": null
}
```

_exec_
```bash
jq . valid.json
```

_output_
```bash
Valid JSON (output shown)
```

Properly formatted, valid JSON structure.

- All keys are quoted strings.
- All values are valid JSON types.
- No trailing commas.

#### Invalid structure examples

```json
{
  name: "John",
  age: 30,
  active: true,
  roles: ["admin", "user",]
}
```

_exec_
```bash
jq . invalid.json 2>&1
```

_output_
```bash
parse error: Invalid JSON
```

Common mistakes that make JSON invalid.

- Keys must be quoted (single or double).
- Trailing commas are not allowed.
- Values like true/false must be unquoted.

#### Common JSON errors

```json
{
  "valid_key": "value",
  'invalid_key': "value",
  "no_comma" "next_key",
  "trailing": "comma",
}
```

_exec_
```bash
echo 'Show validation errors'
```

_output_
```bash
Multiple errors detected
```

Multiple common JSON validation errors.

- Single quotes not allowed for keys or strings.
- Missing commas between pairs.
- Trailing comma after last element.

**Best practices:**

- Always validate JSON before deployment.
- Use a JSON linter or validator tool.
- Follow JSON specification strictly.

**Common errors:**

- **Single quotes instead of double quotes**: JSON requires double quotes for all strings and keys.
- **Trailing comma in object or array**: Remove comma after final element.
- **Unquoted keys**: All keys must be quoted strings.

**Advanced notes:**

- **Validation Tools:** Use jq, jsonlint, or online validators to check JSON syntax.

### Formatting and Style

JSON formatting, indentation, and style conventions.

**Keywords:** formatting, style, indentation, pretty-print, minification

#### Pretty-printed JSON

```json
{
  "user": {
    "id": 1,
    "name": "Alice",
    "tags": ["admin", "verified"],
    "active": true
  }
}
```

_exec_
```bash
jq . user.json
```

_output_
```json
{
  "user": {
    "id": 1,
    "name": "Alice",
    "tags": [
      "admin",
      "verified"
    ],
    "active": true
  }
}
```

Well-formatted JSON with 2-space indentation.

- Improves readability and debugging.
- Standard in development.
- 2-4 spaces recommended for indentation.

#### Minified JSON

```json
{"user":{"id":1,"name":"Alice","tags":["admin","verified"],"active":true}}
```

_exec_
```bash
jq -c . user.json
```

_output_
```bash
{"user":{"id":1,"name":"Alice","tags":["admin","verified"],"active":true}}
```

Minified JSON with no whitespace.

- Reduces file size for transmission.
- Standard for production/APIs.
- Harder to read manually.

#### Indentation standards

```json
{
    "level": 1,
    "nested": {
        "level": 2,
        "items": [
            "first",
            "second"
        ]
    }
}
```

_exec_
```bash
jq --indent 4 . file.json
```

_output_
```bash
4-space indentation
```

JSON with 4-space indentation standard.

- Some organizations prefer 4 spaces over 2.
- Consistency important within project.

**Best practices:**

- Use 2-4 spaces for indentation consistently.
- Format for development, minify for production.
- Document indentation standard for project.

**Common errors:**

- **Inconsistent indentation**: Use automated formatter like Prettier.
- **Tabs for indentation**: Use spaces consistently (2 or 4).

**Advanced notes:**

- **Automated Formatting:** Use tools like Prettier, jq --indent, or JSON formatters.

### Parsing and Use

Parsing JSON and using it in applications.

**Keywords:** parsing, loading, conversion, objects, deserialization

#### JavaScript JSON parsing

```json
{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}
```

_exec_
```bash
node -e "const data = JSON.parse('{\"name\": \"John\"}'); console.log(data.name);"
```

_output_
```bash
John
```

Parsing JSON string to JavaScript object.

- JSON.parse() converts string to object.
- JSON.stringify() converts object to string.

#### Python JSON parsing

```json
{
  "product": "Laptop",
  "price": 999.99,
  "available": true
}
```

_exec_
```bash
python3 -c "import json; data = json.loads('{\"product\": \"Laptop\"}'); print(data['product'])"
```

_output_
```bash
Laptop
```

Parsing JSON string to Python dictionary.

- json.loads() parses JSON string.
- json.load() reads from file.

#### Validation with schema

```json
{
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "age": {"type": "integer"},
    "email": {"type": "string"}
  },
  "required": ["name", "email"]
}
```

_exec_
```bash
echo 'JSON Schema validation'
```

_output_
```bash
Schema validates structure
```

JSON Schema for validating data structure.

- Schema defines expected structure.
- Tools validate data against schema.

**Best practices:**

- Always validate JSON before using in application.
- Use appropriate parsing method for language.
- Handle parsing errors gracefully.

**Common errors:**

- **Not handling parse errors**: Use try-catch blocks for parsing.
- **Assuming valid JSON**: Validate JSON before processing.

**Advanced notes:**

- **Schema Validation:** Use JSON Schema (JSON Schema Draft 7+) for comprehensive validation.
- **Error Handling:** Implement proper error handling for malformed JSON.
