---
title: "JSON"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/json
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# JSON

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, and every mainstream programming language can read it.

6 Categories18 Sections54 ExamplesPublished: 01 Jun 2023Updated: 28 Feb 2025

JSONData FormatData SerializationObjectsArraysSyntaxValidationParsing

[Markdown for AI(opens in a new tab)](/json/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Config & Data Formats](/series/config--data-formats)3/5

[PreviousYAML](/cheatsheets/yaml)[NextMarkdown](/cheatsheets/markdown)

All posts in this series (5)

Cheatsheets5

1.  [RegEx](/cheatsheets/regex)
2.  [YAML](/cheatsheets/yaml)
3.  [JSONYou are here](/cheatsheets/json)
4.  [Markdown](/cheatsheets/markdown)
5.  [TOML](/cheatsheets/toml)

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](#category-getting-started)

-   [Basic Structure](#section-basic-structure)
-   [Data Types](#section-data-types)
-   [Whitespace and Comments](#section-whitespace-and-comments)

[Objects](#category-objects)

-   [Object Syntax](#section-object-syntax)
-   [Object Keys](#section-object-keys)
-   [Object Values](#section-object-values)

[Arrays](#category-arrays)

-   [Array Syntax](#section-array-syntax)
-   [Array Elements](#section-array-elements)
-   [Array Operations](#section-array-operations)

[Strings and Numbers](#category-strings-and-numbers)

-   [String Format](#section-string-format)
-   [String Escapes](#section-string-escapes)
-   [Number Format](#section-number-format)

[Complex Structures](#category-complex-structures)

-   [Nested Objects](#section-nested-objects)
-   [Nested Arrays](#section-nested-arrays)
-   [Mixed Structures](#section-mixed-structures)

[Validation and Best Practices](#category-validation-and-best-practices)

-   [Valid JSON](#section-valid-json)
-   [Formatting and Style](#section-formatting-and-style)
-   [Parsing and Use](#section-parsing-and-use)

No commands found

Try adjusting your search term

## Getting Started

Fundamental JSON concepts and syntax for beginners.

### Basic Structure

Understanding JSON file structure and format.

#### Accessibility

Ensure JSON output is properly formatted for readability.

#### 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.

#### Keywords

structureJSONformatsyntaxvalid

[Learn more](https://www.json.org/)

#### Minimal JSON object

The simplest valid JSON structure is an empty object.

Code

```
1{}
```

Execution

Terminal window

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

Output

```
1{}
```

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

#### Valid JSON structure

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

Code

```
1{2  "name": "John",3  "age": 30,4  "city": "New York"5}
```

Execution

Terminal window

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

Output

```
1{2  "name": "John",3  "age": 30,4  "city": "New York"5}
```

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

#### JSON file format

A typical JSON file structure for configuration data.

Code

```
1{2  "version": "1.0",3  "author": "Admin",4  "timestamp": "2025-02-28"5}
```

Execution

Terminal window

```
cat config.json | jq .
```

Output

```
1{2  "version": "1.0",3  "author": "Admin",4  "timestamp": "2025-02-28"5}
```

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

### Data Types

JSON data types and their usage.

#### Accessibility

Label each data type clearly with examples.

#### 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.

#### Keywords

data typesJSONobjectsarraysstringsnumbersboolean

[Learn more](https://www.json.org/json-en.html)

#### All JSON data types

Demonstrates all seven JSON data types.

Code

```
1{2  "string": "Hello",3  "number": 42,4  "decimal": 3.14,5  "boolean_true": true,6  "boolean_false": false,7  "null_value": null,8  "array": [1, 2, 3],9  "object": {"key": "value"}10}
```

Execution

Terminal window

```
jq . data.json
```

Output

```
1{2  "string": "Hello",3  "number": 42,4  "decimal": 3.14,5  "boolean_true": true,6  "boolean_false": false,7  "null_value": null,8  "array": [1, 2, 3],9  "object": {"key": "value"}10}
```

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

#### Type examples

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

Code

```
1{2  "user": {3    "id": 123,4    "active": true,5    "score": 98.5,6    "notes": null,7    "tags": ["admin", "verified"]8  }9}
```

Execution

Terminal window

```
jq '.user' user.json
```

Output

```
1{2  "id": 123,3  "active": true,4  "score": 98.5,5  "notes": null,6  "tags": ["admin", "verified"]7}
```

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

#### Multiple types in array

Arrays can contain any combination of JSON data types.

Code

```
1{2  "mixed": [3    "string",4    42,5    true,6    null,7    {"nested": "object"},8    [1, 2, 3]9  ]10}
```

Execution

Terminal window

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

Output

Terminal window

```
6
```

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

### Whitespace and Comments

Handling whitespace, formatting, and comments in JSON.

#### Accessibility

Ensure formatted output is clear and accessible.

#### 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, and VS Code config files use it.
-   **Standards:** RFC 7159 defines the JSON format. Whitespace is insignificant outside strings.

#### Keywords

whitespaceformattingcommentsindentationpretty-print

[Learn more](https://www.json.org/)

#### Formatted JSON

Pretty-printed JSON with indentation for readability.

Code

```
1{2  "name": "Alice",3  "age": 28,4  "email": "alice@example.com"5}
```

Execution

Terminal window

```
jq . user.json
```

Output

```
1{2  "name": "Alice",3  "age": 28,4  "email": "alice@example.com"5}
```

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

#### Minified JSON

Minified JSON removes all unnecessary whitespace for smaller file size.

Code

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

Execution

Terminal window

```
jq -c . user.json
```

Output

Terminal window

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

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

#### Pretty-printed with indentation

JSON with 4-space indentation standard.

Code

```
1{2    "user": {3        "id": 1,4        "details": {5            "name": "Carol",6            "role": "admin"7        }8    }9}
```

Execution

Terminal window

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

Output

Terminal window

```
4-space indentation applied
```

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

## Objects

Working with JSON objects and key-value pairs.

### Object Syntax

Understanding JSON object structure and syntax.

#### Accessibility

Clearly label object structure and nested content.

#### 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.

#### Keywords

objectssyntaxbraceskey-valuepairs

[Learn more](https://www.json.org/)

#### Empty object

An empty object contains no key-value pairs.

Code

```
1{}
```

Execution

Terminal window

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

Output

Terminal window

```
"object"
```

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

#### Simple object

A simple object with three key-value pairs.

Code

```
1{2  "firstName": "John",3  "lastName": "Doe",4  "age": 305}
```

Execution

Terminal window

```
jq . person.json
```

Output

```
1{2  "firstName": "John",3  "lastName": "Doe",4  "age": 305}
```

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

#### Nested object

Objects can be nested within other objects.

Code

```
1{2  "person": {3    "name": "Jane",4    "contact": {5      "email": "jane@example.com",6      "phone": "555-1234"7    }8  }9}
```

Execution

Terminal window

```
jq '.person.contact' person.json
```

Output

```
1{2  "email": "jane@example.com",3  "phone": "555-1234"4}
```

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

### Object Keys

Understanding JSON object key naming and conventions.

#### Accessibility

Provide clear examples of valid and invalid key formats.

#### 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 and the 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.

#### Keywords

keysnamingconventionsstringsidentifiers

[Learn more](https://www.json.org/)

#### Simple key names

Standard key names that follow common conventions.

Code

```
1{2  "id": 1,3  "name": "Alice",4  "email": "alice@example.com",5  "verified": true6}
```

Execution

Terminal window

```
jq 'keys' user.json
```

Output

```
1[2  "email",3  "id",4  "name",5  "verified"6]
```

-   Use camelCase or snake\_case consistently.
-   Keep key names short and descriptive.

#### Keys with spaces

Keys can contain spaces if enclosed in double quotes.

Code

```
1{2  "first name": "John",3  "last name": "Smith",4  "home address": "123 Main St"5}
```

Execution

Terminal window

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

Output

Terminal window

```
"John"
```

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

#### Keys with special characters

Keys can contain special characters but must be quoted.

Code

```
1{2  "@id": "obj-123",3  "$type": "Person",4  "api-key": "abc123xyz",5  "time&date": "2025-02-28"6}
```

Execution

Terminal window

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

Output

Terminal window

```
"obj-123"
```

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

### Object Values

Understanding JSON object values and nesting.

#### Accessibility

Show clear examples of various value types.

#### 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.

#### Keywords

valuesnestingtypesheterogeneoushomogeneous

[Learn more](https://www.json.org/)

#### Different value types

Objects can contain any valid JSON value.

Code

```
1{2  "stringValue": "text",3  "numberValue": 42,4  "decimalValue": 3.14,5  "booleanValue": true,6  "nullValue": null,7  "arrayValue": [1, 2, 3],8  "objectValue": {"nested": true}9}
```

Execution

Terminal window

```
jq '.stringValue' data.json
```

Output

Terminal window

```
"text"
```

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

#### Nested objects as values

Objects can be deeply nested within each other.

Code

```
1{2  "user": {3    "profile": {4      "name": "Bob",5      "age": 356    },7    "settings": {8      "notifications": true,9      "theme": "dark"10    }11  }12}
```

Execution

Terminal window

```
jq '.user.settings' user.json
```

Output

```
1{2  "notifications": true,3  "theme": "dark"4}
```

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

#### Array values in objects

Objects can contain arrays as values.

Code

```
1{2  "user": "Carol",3  "hobbies": ["reading", "gaming", "cooking"],4  "scores": [95, 87, 92, 88],5  "contacts": [6    {"type": "email", "value": "carol@example.com"},7    {"type": "phone", "value": "555-5678"}8  ]9}
```

Execution

Terminal window

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

Output

Terminal window

```
"reading"
```

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

## Arrays

Working with JSON arrays and list structures.

### Array Syntax

Understanding JSON array structure and syntax.

#### Accessibility

Clearly label array elements and positions.

#### 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.

#### Keywords

arrayssyntaxbracketselementslists

[Learn more](https://www.json.org/)

#### Empty array

An empty array contains no elements.

Code

```
1[]
```

Execution

Terminal window

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

Output

Terminal window

```
"array"
```

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

#### Simple array

A simple array of strings.

Code

```
1[2  "apple",3  "banana",4  "cherry"5]
```

Execution

Terminal window

```
jq . fruits.json
```

Output

```
1[2  "apple",3  "banana",4  "cherry"5]
```

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

#### Mixed types array

Arrays can contain heterogeneous types.

Code

```
1[2  "string",3  42,4  true,5  null,6  {"key": "value"},7  [1, 2, 3]8]
```

Execution

Terminal window

```
jq 'length' mixed.json
```

Output

Terminal window

```
6
```

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

### Array Elements

Understanding JSON array element types and access.

#### Accessibility

Provide clear index labels for array elements.

#### 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.

#### Keywords

elementsitemsvaluesindexingaccess

[Learn more](https://www.json.org/)

#### Array of objects

Array containing objects.

Code

```
1[2  {3    "id": 1,4    "name": "Alice",5    "role": "admin"6  },7  {8    "id": 2,9    "name": "Bob",10    "role": "user"11  }12]
```

Execution

Terminal window

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

Output

Terminal window

```
"Alice"
```

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

#### Nested arrays

Array of arrays (2D matrix structure).

Code

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

Execution

Terminal window

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

Output

Terminal window

```
6
```

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

#### Homogeneous array

Arrays with all elements of same type.

Code

```
1{2  "scores": [95, 87, 92, 88, 91],3  "temperatures": [72.5, 68.3, 75.1, 69.8]4}
```

Execution

Terminal window

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

Output

Terminal window

```
5
```

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

### Array Operations

Common operations with JSON arrays.

#### Accessibility

Show clear operation examples with results.

#### 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.

#### Keywords

operationsindexingiterationlengthaccess

[Learn more](https://www.json.org/)

#### Accessing array elements

Access array element by zero-based index.

Code

```
1{2  "colors": [3    "red",4    "green",5    "blue",6    "yellow"7  ]8}
```

Execution

Terminal window

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

Output

Terminal window

```
"blue"
```

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

#### Array length

Get the number of elements in an array.

Code

```
1{2  "items": ["apple", "banana", "cherry", "date"]3}
```

Execution

Terminal window

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

Output

Terminal window

```
4
```

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

#### Slicing arrays

Extract subset of array elements.

Code

```
1{2  "numbers": [10, 20, 30, 40, 50, 60]3}
```

Execution

Terminal window

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

Output

```
1[2  30,3  40,4  505]
```

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

## Strings and Numbers

Working with JSON strings and numeric values.

### String Format

Understanding JSON string format and syntax.

#### Accessibility

Show clear string examples with special characters.

#### 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.

#### Keywords

stringsformatquotestextcharacters

[Learn more](https://www.json.org/)

#### Simple strings

Basic string values enclosed in double quotes.

Code

```
1{2  "greeting": "Hello",3  "sentence": "This is a complete sentence.",4  "empty": ""5}
```

Execution

Terminal window

```
jq '.greeting' strings.json
```

Output

Terminal window

```
"Hello"
```

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

#### Escaped characters

Strings with escape sequences for special characters.

Code

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

Execution

Terminal window

```
jq '.newline' strings.json
```

Output

Terminal window

```
"Line 1Line 2"
```

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

#### Unicode strings

Strings can contain Unicode characters and emojis.

Code

```
1{2  "emoji": "Hello 👋",3  "chinese": "你好",4  "unicode": "A\u0301"5}
```

Execution

Terminal window

```
jq '.emoji' unicode.json
```

Output

Terminal window

```
"Hello 👋"
```

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

### String Escapes

Understanding JSON escape sequences.

#### Accessibility

Show each escape sequence with its effect.

#### 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 for JSON to be valid.

#### Keywords

escapessequencesspecial charactersformattingunicode

[Learn more](https://www.json.org/)

#### Common escape sequences

Common escape sequences in JSON strings.

Code

```
1{2  "quote": "He said \"Hello\"",3  "backslash": "Path: C:\\Users\\",4  "newline": "First\nSecond",5  "tab": "Col1\tCol2",6  "carriage_return": "Line1\rLine2"7}
```

Execution

Terminal window

```
jq '.quote' escapes.json
```

Output

Terminal window

```
"He said \"Hello\""
```

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

#### All escape sequences

All eight JSON escape sequences.

Code

```
1{2  "quote": "\"",3  "backslash": "\\",4  "forward_slash": "/",5  "backspace": "\b",6  "form_feed": "\f",7  "newline": "\n",8  "carriage_return": "\r",9  "tab": "\t"10}
```

Execution

Terminal window

```
jq 'keys' escapes.json
```

Output

```
1[2  "backslash",3  "backspace",4  "carriage_return",5  "form_feed",6  "forward_slash",7  "newline",8  "quote",9  "tab"10]
```

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

#### Unicode escape sequences

Unicode escape sequences using \\uXXXX notation.

Code

```
1{2  "copyright": "\u00A9 2025",3  "greek": "\u03B1 (alpha)",4  "emoji_unicode": "\uD83D\uDC4B"5}
```

Execution

Terminal window

```
jq '.copyright' unicode.json
```

Output

Terminal window

```
"© 2025"
```

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

### Number Format

Understanding JSON number formatting.

#### Accessibility

Show number format examples clearly.

#### 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.

#### Keywords

numbersintegersdecimalsscientificnotation

[Learn more](https://www.json.org/)

#### Integer numbers

Integer values without decimal points.

Code

```
1{2  "year": 2025,3  "count": 42,4  "negative": -100,5  "zero": 0,6  "large": 10000007}
```

Execution

Terminal window

```
jq '.year' numbers.json
```

Output

Terminal window

```
2025
```

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

#### Decimal numbers

Decimal (floating-point) numbers.

Code

```
1{2  "pi": 3.14159,3  "price": 19.99,4  "temperature": -5.5,5  "percentage": 0.956}
```

Execution

Terminal window

```
jq '.pi' decimals.json
```

Output

Terminal window

```
3.14159
```

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

#### Scientific notation

Numbers in scientific notation.

Code

```
1{2  "avogadro": 6.02214076e+23,3  "tiny": 1.6e-19,4  "standard": 1.5e25}
```

Execution

Terminal window

```
jq '.avogadro' scientific.json
```

Output

Terminal window

```
6.02214076e+23
```

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

## Complex Structures

Building complex JSON data structures.

### Nested Objects

Working with objects nested within other objects.

#### Accessibility

Show nested structure with clear hierarchy.

#### 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.

#### Keywords

nestedobjectshierarchydeepnesting

[Learn more](https://www.json.org/)

#### Two-level nesting

Basic nested object structure.

Code

```
1{2  "person": {3    "name": "Alice",4    "age": 305  }6}
```

Execution

Terminal window

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

Output

Terminal window

```
"Alice"
```

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

#### Multi-level nesting

Deep nesting of multiple object levels.

Code

```
1{2  "company": {3    "department": {4      "team": {5        "lead": "Bob",6        "size": 57      }8    }9  }10}
```

Execution

Terminal window

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

Output

Terminal window

```
"Bob"
```

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

#### Complex hierarchy

Complex hierarchical configuration structure.

Code

```
1{2  "application": {3    "name": "MyApp",4    "version": "1.0",5    "config": {6      "database": {7        "host": "localhost",8        "port": 5432,9        "credentials": {10          "user": "admin",11          "password": "secret"12        }13      }14    }15  }16}
```

Execution

Terminal window

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

Output

Terminal window

```
"localhost"
```

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

### Nested Arrays

Working with arrays nested within other structures.

#### Accessibility

Show clear array nesting patterns.

#### 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.

#### Keywords

nestedarrayscollectionsmulti-dimensionallists

[Learn more](https://www.json.org/)

#### Array of arrays

Two-dimensional array structure.

Code

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

Execution

Terminal window

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

Output

Terminal window

```
6
```

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

#### Array of objects

Common structure for collections of entities.

Code

```
1{2  "users": [3    {4      "id": 1,5      "name": "Alice",6      "email": "alice@example.com"7    },8    {9      "id": 2,10      "name": "Bob",11      "email": "bob@example.com"12    }13  ]14}
```

Execution

Terminal window

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

Output

Terminal window

```
"alice@example.com"
```

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

#### Complex nesting

Complex nested array and object combination.

Code

```
1{2  "departments": [3    {4      "name": "Engineering",5      "members": [6        {"name": "Alice", "roles": ["dev", "lead"]},7        {"name": "Bob", "roles": ["dev", "devops"]}8      ]9    },10    {11      "name": "Sales",12      "members": [13        {"name": "Carol", "roles": ["sales"]}14      ]15    }16  ]17}
```

Execution

Terminal window

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

Output

Terminal window

```
"dev"
```

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

### Mixed Structures

Combining objects and arrays in real-world structures.

#### Accessibility

Show realistic examples with clear organization.

#### 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:** Give all array items the same properties.
-   **Over-nesting or over-flattening:** Balance between clarity and depth.

#### Keywords

mixedstructuresreal-worldpatternsapi

[Learn more](https://www.json.org/)

#### API response structure

Typical API response with status and nested data.

Code

```
1{2  "status": "success",3  "data": {4    "items": [5      {6        "id": 1,7        "title": "Item 1",8        "price": 29.999      },10      {11        "id": 2,12        "title": "Item 2",13        "price": 39.9914      }15    ],16    "pagination": {17      "page": 1,18      "total": 5019    }20  }21}
```

Execution

Terminal window

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

Output

Terminal window

```
"Item 1"
```

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

#### Configuration structure

Configuration combining objects and array of objects.

Code

```
1{2  "server": {3    "host": "localhost",4    "port": 3000,5    "endpoints": [6      {7        "path": "/api/users",8        "method": "GET"9      },10      {11        "path": "/api/users",12        "method": "POST"13      }14    ]15  }16}
```

Execution

Terminal window

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

Output

Terminal window

```
"/api/users"
```

-   Used for application configuration.
-   Organizes settings hierarchically.

#### Data model structure

A full data model with mixed nesting.

Code

```
1{2  "user": {3    "id": 123,4    "profile": {5      "firstName": "John",6      "lastName": "Doe",7      "avatar": "https://example.com/avatar.jpg"8    },9    "subscriptions": [10      {11        "plan": "premium",12        "renewalDate": "2025-03-28"13      }14    ],15    "preferences": {16      "notifications": true,17      "themes": ["dark", "light"]18    }19  }20}
```

Execution

Terminal window

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

Output

Terminal window

```
"dark"
```

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

## Validation and Best Practices

Validating and properly formatting JSON data.

### Valid JSON

Valid JSON structure and common mistakes.

#### Accessibility

Show valid and invalid examples clearly labeled.

#### 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.

#### Keywords

validationvalidinvalidsyntaxerrors

[Learn more](https://www.json.org/)

#### Valid JSON structure

Properly formatted, valid JSON structure.

Code

```
1{2  "name": "John",3  "age": 30,4  "email": "john@example.com",5  "active": true,6  "roles": ["admin", "user"],7  "metadata": null8}
```

Execution

Terminal window

```
jq . valid.json
```

Output

Terminal window

```
Valid JSON (output shown)
```

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

#### Invalid structure examples

Common mistakes that make JSON invalid.

Code

```
1{2  name: "John",3  age: 30,4  active: true,5  roles: ["admin", "user",]6}
```

Execution

Terminal window

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

Output

Terminal window

```
parse error: Invalid JSON
```

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

#### Common JSON errors

Multiple common JSON validation errors.

Code

```
1{2  "valid_key": "value",3  'invalid_key': "value",4  "no_comma" "next_key",5  "trailing": "comma",6}
```

Execution

Terminal window

```
echo 'Show validation errors'
```

Output

Terminal window

```
Multiple errors detected
```

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

### Formatting and Style

JSON formatting, indentation, and style conventions.

#### Accessibility

Show formatted and minified examples side-by-side.

#### 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.

#### Keywords

formattingstyleindentationpretty-printminification

[Learn more](https://www.json.org/)

#### Pretty-printed JSON

Well-formatted JSON with 2-space indentation.

Code

```
1{2  "user": {3    "id": 1,4    "name": "Alice",5    "tags": ["admin", "verified"],6    "active": true7  }8}
```

Execution

Terminal window

```
jq . user.json
```

Output

```
1{2  "user": {3    "id": 1,4    "name": "Alice",5    "tags": [6      "admin",7      "verified"8    ],9    "active": true10  }11}
```

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

#### Minified JSON

Minified JSON with no whitespace.

Code

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

Execution

Terminal window

```
jq -c . user.json
```

Output

Terminal window

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

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

#### Indentation standards

JSON with 4-space indentation standard.

Code

```
1{2    "level": 1,3    "nested": {4        "level": 2,5        "items": [6            "first",7            "second"8        ]9    }10}
```

Execution

Terminal window

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

Output

Terminal window

```
4-space indentation
```

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

### Parsing and Use

Parsing JSON and using it in applications.

#### Accessibility

Show parsing examples across languages.

#### 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 thorough validation.
-   **Error Handling:** Implement proper error handling for malformed JSON.

#### Keywords

parsingloadingconversionobjectsdeserialization

[Learn more](https://www.json.org/)

#### JavaScript JSON parsing

Parsing JSON string to JavaScript object.

Code

```
1{2  "name": "John",3  "age": 30,4  "email": "john@example.com"5}
```

Execution

Terminal window

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

Output

Terminal window

```
John
```

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

#### Python JSON parsing

Parsing JSON string to Python dictionary.

Code

```
1{2  "product": "Laptop",3  "price": 999.99,4  "available": true5}
```

Execution

Terminal window

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

Output

Terminal window

```
Laptop
```

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

#### Validation with schema

JSON Schema for validating data structure.

Code

```
1{2  "type": "object",3  "properties": {4    "name": {"type": "string"},5    "age": {"type": "integer"},6    "email": {"type": "string"}7  },8  "required": ["name", "email"]9}
```

Execution

Terminal window

```
echo 'JSON Schema validation'
```

Output

Terminal window

```
Schema validates structure
```

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

Was this useful?

## Tags

#JSON#Data Format#Data Serialization#Objects#Arrays#Syntax#Validation#Parsing

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=JSON&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson&title=JSON&summary=JSON%20\(JavaScript%20Object%20Notation\)%20is%20a%20lightweight%2C%20text-based%20data%20format%20used%20for%20data%20exchange.%20It%20supports%20objects%2C%20arrays%2C%20strings%2C%20numbers%2C%20booleans%2C%20and%20null%20values%2C%20and%20every%20mainstream%20programming%20language%20can%20read%20it.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=JSON%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson&text=JSON "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson&title=JSON "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson&t=JSON "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson&media=&description=JSON%20\(JavaScript%20Object%20Notation\)%20is%20a%20lightweight%2C%20text-based%20data%20format%20used%20for%20data%20exchange.%20It%20supports%20objects%2C%20arrays%2C%20strings%2C%20numbers%2C%20booleans%2C%20and%20null%20values%2C%20and%20every%20mainstream%20programming%20language%20can%20read%20it. "Share on Pinterest")[Email](<mailto:?subject=JSON&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fjson>)

## Comments

## You might also enjoy

More posts on similar topics

## [YAML](/cheatsheets/yaml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   YAML
-   Configuration
-   Data Serialization
-   DevOps
-   Infrastructure

YAML (YAML Ain't Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and uses ind

#YAML#Configuration#Data Serialization+6 tags

[read more](/cheatsheets/yaml)

## [TOML](/cheatsheets/toml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   TOML
-   Configuration
-   Data Serialization
-   Settings

TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration file format. Designed to be minimal, readable, and unambiguous, it's used extensively in package manifests (like Cargo.toml and

#TOML#Configuration#Data Format+5 tags

[read more](/cheatsheets/toml)

## [RegEx](/cheatsheets/regex)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Tools
-   Regular Expressions
-   Text Processing
-   Pattern Matching
-   Development

Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They handle pattern matching, validation, and text processing across nearly all programming language

#RegEx#Regular Expressions#Pattern Matching+5 tags

[read more](/cheatsheets/regex)

## [Markdown](/cheatsheets/markdown)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Markup Language
-   Markdown
-   Documentation
-   Formatting
-   Content Creation
-   Writing

Markdown is a lightweight markup language for writing formatted content with a simple, readable syntax. It was created for writing on the web, and is now used in documentation, blogs, and note-taking

#Markdown#Formatting#Text+6 tags

[read more](/cheatsheets/markdown)

## [JavaScript](/cheatsheets/javascript)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Web Development
-   Frontend
-   Backend
-   Scripting

JavaScript is a high-level programming language that powers the web. It supports object-oriented, functional, and event-driven programming styles. The sections below cover JavaScript syntax and metho

#JavaScript#ES6#Web Development+3 tags

[read more](/cheatsheets/javascript)

5 related posts
