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:
- Text values enclosed in double quotes (
"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
orfalse
(no quotes). - Example:
- Logical values represented as
"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:
- Ordered collection of values enclosed in square brackets (
"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:
- Unordered collection of key-value pairs enclosed in curly braces (
"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
- JSON does not support functions, date objects, or undefined values.
- All keys in JSON objects must be strings enclosed in double quotes.
- JSON is case-sensitive.
For in-depth tutorials and more examples, visit The Coding College.