JSON Data Types

JSON (JavaScript Object Notation) supports several data types to ensure flexibility and simplicity when representing structured data. Each data type is used to encode specific kinds of information in JSON-formatted strings.

Primary Data Types in JSON

  • String:
    • Text values enclosed in double quotes (").
    • Example:
"name": "Alice"
  • Rules:
    • Must use double quotes.
    • Special characters (e.g., newline, tab) are escaped with a backslash (\).
  • Number:
    • Numeric values without quotes.
    • Supports both integers and floating-point numbers.
    • Example:
"age": 30,
"score": 99.5
  • Rules:
    • No distinction between integers and floats.
    • Cannot include NaN, Infinity, or -Infinity.
  • Boolean:
    • Logical values represented as true or false (no quotes).
    • Example:
"isStudent": false
  • Null:
    • Represents a null or empty value.
    • Example:
"middleName": null
  • Array:
    • Ordered collection of values enclosed in square brackets ([]).
    • Elements can be of any JSON data type.
    • Example:
"fruits": ["apple", "banana", "cherry"]
  • Object:
    • Unordered collection of key-value pairs enclosed in curly braces ({}).
    • Keys are strings, and values can be any JSON data type.
    • Example:
"person": {
    "firstName": "John",
    "lastName": "Doe",
    "age": 25
}

Nested Data Structures

JSON allows nesting of objects and arrays to represent more complex data.

Example: Nested Object

{
    "user": {
        "id": 101,
        "profile": {
            "name": "Alice",
            "email": "[email protected]"
        }
    }
}

Example: Array of Objects

{
    "students": [
        {"id": 1, "name": "John"},
        {"id": 2, "name": "Jane"}
    ]
}

Key Points to Remember

  1. JSON does not support functions, date objects, or undefined values.
  2. All keys in JSON objects must be strings enclosed in double quotes.
  3. JSON is case-sensitive.

For in-depth tutorials and more examples, visit The Coding College.

Leave a Comment