Data Exchange Format
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between a server and a client.
JSON is essentially text written in JavaScript object notation, making it easy to convert between JavaScript objects and JSON strings.
It's the standard format for APIs, configuration files, and data storage, supported by virtually all programming languages.
// JavaScript Object
const person = {
name: "Alice",
age: 30,
email: "alice@example.com",
hobbies: ["reading", "coding", "gaming"],
address: {
city: "New York",
country: "USA"
}
};
// Convert JavaScript object to JSON string
const jsonString = JSON.stringify(person);
console.log(jsonString);
// '{"name":"Alice","age":30,"email":"alice@example.com",...}'
// Formatted JSON with indentation
const prettyJson = JSON.stringify(person, null, 2);
console.log(prettyJson);
// Convert JSON string back to JavaScript object
const jsonText = '{"name":"Bob","age":25}';
const obj = JSON.parse(jsonText);
console.log(obj.name); // "Bob"
// Handling parse errors
try {
const badJson = '{name: "Invalid"}'; // Missing quotes
const parsed = JSON.parse(badJson);
} catch (error) {
console.error('JSON parsing error:', error.message);
}
// Filter properties when stringifying
const filtered = JSON.stringify(person, ['name', 'email']);
// Only includes name and email properties
- JSON.stringify() - Convert JavaScript object to JSON string
- JSON.parse() - Convert JSON string to JavaScript object
- Data Types: String, Number, Boolean, Array, Object, null
- Not Supported: Functions, undefined, Date objects (converted to string)
- Syntax Rules: Keys must be in double quotes, no trailing commas
- Pretty Printing: Use stringify(obj, null, 2) for formatted output
- Error Handling: Use try/catch for JSON.parse() to handle invalid JSON
Try JSON Operations
<div class="json-demo">
<h3>JSON Examples</h3>
<div class="example">
<h4>1. Object to JSON</h4>
<textarea id="jsObject" rows="6">
{
"name": "John Doe",
"age": 28,
"skills": ["JavaScript", "Python", "CSS"],
"active": true
}</textarea>
<button id="toJsonBtn">Convert to JSON String</button>
<div id="jsonOutput"></div>
</div>
<div class="example">
<h4>2. JSON to Object</h4>
<textarea id="jsonString" rows="4">{"product":"Laptop","price":999,"inStock":true}</textarea>
<button id="parseJsonBtn">Parse JSON</button>
<div id="parseOutput"></div>
</div>
<div class="example">
<h4>3. Test JSON Validity</h4>
<textarea id="testJson" rows="4">{"valid": "json", "number": 42}</textarea>
<button id="validateBtn">Validate JSON</button>
<div id="validateOutput"></div>
</div>
</div>
Note: Security: Never use eval() to parse JSON - always use JSON.parse() to prevent code injection attacks.
Note: Dates: JSON doesn't have a Date type. Dates are converted to ISO 8601 strings and must be converted back manually.
Note: Deep Copy: JSON.parse(JSON.stringify(obj)) creates a deep copy, but loses functions and special objects.