JSON Reference
Basic Structure
JSON (JavaScript Object Notation) is a lightweight data format that's easy to read and write. The basic structure consists of key-value pairs.
{
"key": "value"
}
Data Types
JSON supports several data types including strings, numbers, booleans, null, arrays, and objects.
{
"string": "Hello, World!",
"number": 42,
"float": 3.14,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}
Arrays
Arrays in JSON are ordered collections of values, which can be of any type.
[
"apple",
"banana",
"orange"
]
Nested Objects
JSON objects can contain other objects and arrays, allowing for complex data structures.
{
"user": {
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Boston",
"state": "MA",
"zip": "02108"
},
"hobbies": [
"reading",
"gaming",
"coding"
]
}
}
Common Use Cases
API Response
JSON is commonly used in API responses to structure data in a consistent format.
{
"status": "success",
"data": {
"id": 1,
"title": "Example Post",
"content": "This is a sample post",
"author": {
"id": 1,
"name": "John Doe"
},
"comments": [
{
"id": 1,
"text": "Great post!",
"user": "Alice"
}
]
}
}
Configuration
JSON is often used for configuration files due to its readability and structure.
{
"app": {
"name": "My App",
"version": "1.0.0",
"settings": {
"theme": "dark",
"language": "en",
"notifications": true
}
}
}
Working with JSON in JavaScript
JavaScript provides built-in methods to work with JSON data. Here are the most common operations:
// Parse JSON string to object
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
// Convert object to JSON string
const person = {
name: "John",
age: 30
};
const json = JSON.stringify(person);