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.
Example
// 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
HTML
<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> CSS
.json-demo {
padding: 20px;
max-width: 700px;
}
.example {
margin: 20px 0;
padding: 15px;
background: #f5f5f5;
border-radius: 8px;
}
h4 {
margin-top: 0;
color: #333;
}
textarea {
width: 100%;
padding: 10px;
font-family: 'Courier New', monospace;
font-size: 13px;
border: 2px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
resize: vertical;
}
button {
padding: 10px 15px;
margin: 10px 0;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
button:hover {
background: #1976D2;
}
#jsonOutput, #parseOutput, #validateOutput {
margin-top: 10px;
padding: 12px;
background: white;
border: 2px solid #ddd;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 13px;
white-space: pre-wrap;
max-height: 300px;
overflow-y: auto;
}
.success {
border-color: #4CAF50 !important;
background-color: #e8f5e9 !important;
}
.error {
border-color: #f44336 !important;
background-color: #ffebee !important;
color: #c62828;
} JavaScript
// Example 1: Object to JSON String
document.getElementById('toJsonBtn').addEventListener('click', function() {
const output = document.getElementById('jsonOutput');
try {
const jsObjectText = document.getElementById('jsObject').value;
const obj = JSON.parse(jsObjectText);
// Convert to formatted JSON
const jsonString = JSON.stringify(obj, null, 2);
output.textContent = 'JSON String:\n' + jsonString;
output.className = 'success';
// Show character count
output.textContent += `\n\nCharacters: ${jsonString.length}`;
} catch (error) {
output.className = 'error';
output.textContent = 'Error: ' + error.message;
}
});
// Example 2: JSON String to Object
document.getElementById('parseJsonBtn').addEventListener('click', function() {
const output = document.getElementById('parseOutput');
try {
const jsonString = document.getElementById('jsonString').value;
const obj = JSON.parse(jsonString);
output.innerHTML = '<strong>Parsed Object Properties:</strong><br>';
for (const [key, value] of Object.entries(obj)) {
const type = typeof value;
output.innerHTML += `<br><strong>${key}:</strong> ${value} (type: ${type})`;
}
output.className = 'success';
} catch (error) {
output.className = 'error';
output.textContent = 'Error parsing JSON: ' + error.message;
}
});
// Example 3: Validate JSON
document.getElementById('validateBtn').addEventListener('click', function() {
const output = document.getElementById('validateOutput');
const jsonText = document.getElementById('testJson').value;
try {
const parsed = JSON.parse(jsonText);
output.innerHTML = '<strong>✓ Valid JSON!</strong><br><br>';
output.innerHTML += 'Formatted output:<br>';
output.textContent += JSON.stringify(parsed, null, 2);
output.className = 'success';
} catch (error) {
output.className = 'error';
output.innerHTML = '<strong>✗ Invalid JSON!</strong><br><br>';
output.innerHTML += '<strong>Error:</strong> ' + error.message + '<br><br>';
output.innerHTML += '<strong>Common issues:</strong><br>';
output.innerHTML += '• Keys must be in double quotes<br>';
output.innerHTML += '• No trailing commas<br>';
output.innerHTML += '• Strings must use double quotes<br>';
output.innerHTML += '• No comments allowed';
}
});
// Set example invalid JSON for testing
document.getElementById('testJson').value = `{
"valid": "json",
"number": 42,
"array": [1, 2, 3]
}`; Notes
- Security: Never use eval() to parse JSON - always use JSON.parse() to prevent code injection attacks.
- Dates: JSON doesn't have a Date type. Dates are converted to ISO 8601 strings and must be converted back manually.
- Deep Copy: JSON.parse(JSON.stringify(obj)) creates a deep copy, but loses functions and special objects.
