JSON Fundamentals
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for data exchange between web applications and APIs. Understanding JSON data handling is essential for modern web development, API integration, and data processing.
π Why JSON Matters
π Universal Standard
Supported by all major programming languages and platforms
β‘ Lightweight
Minimal overhead compared to XML and other formats
π₯ Human Readable
Easy to read and write for both humans and machines
π API Integration
Standard format for REST APIs and web services
π± Cross-Platform
Works seamlessly across different platforms and devices
π§ Native JavaScript
Built-in support in JavaScript without external libraries
ποΈ JSON Structure and Syntax
JSON uses a simple, hierarchical structure based on key-value pairs and supports various data types.
π JSON Data Types
Strings
Text data enclosed in double quotes
"name": "John Doe"
Numbers
Integers and floating-point numbers
"age": 30, "price": 19.99
Booleans
True or false values
"active": true, "verified": false
Null
Represents absence of value
"middleName": null
Objects
Collections of key-value pairs
"address": {"street": "123 Main St", "city": "Anytown"}
Arrays
Ordered lists of values
"tags": ["javascript", "json", "api"]
π Complete JSON Example
{
"user": {
"id": 12345,
"name": "John Doe",
"email": "john@example.com",
"active": true,
"profile": {
"age": 30,
"occupation": "Developer",
"skills": ["JavaScript", "Python", "React"],
"address": {
"street": "123 Main Street",
"city": "Anytown",
"country": "USA",
"coordinates": {
"lat": 40.7128,
"lng": -74.0060
}
}
},
"preferences": {
"theme": "dark",
"notifications": true,
"language": "en"
},
"lastLogin": "2024-01-15T10:30:00Z",
"metadata": null
}
}
JSON Parsing and Serialization
π» JavaScript JSON Methods
JavaScript provides built-in methods for parsing JSON strings and converting JavaScript objects to JSON strings.
π₯ JSON.parse()
Convert JSON string to JavaScript object
// Basic parsing
const jsonString = '{"name": "John", "age": 30}';
const user = JSON.parse(jsonString);
console.log(user.name); // "John"
// Parsing with error handling
try {
const data = JSON.parse(jsonString);
console.log("Parsed successfully:", data);
} catch (error) {
console.error("JSON parsing error:", error.message);
}
// Parsing nested JSON
const complexJson = '{
"user": {
"name": "John",
"profile": {"age": 30, "city": "NYC"}
}
}';
const userData = JSON.parse(complexJson);
console.log(userData.user.profile.city); // "NYC"
π€ JSON.stringify()
Convert JavaScript object to JSON string
// Basic serialization
const user = { name: "John", age: 30 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"John","age":30}'
// Pretty printing
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
// {
// "name": "John",
// "age": 30
// }
// Custom serialization with replacer
const data = {
name: "John",
password: "secret123",
createdAt: new Date()
};
const cleanJson = JSON.stringify(data, (key, value) => {
if (key === 'password') return undefined;
if (key === 'createdAt') return value.toISOString();
return value;
});
console.log(cleanJson);
// '{"name":"John","createdAt":"2024-01-15T10:30:00.000Z"}'
π§ Advanced Parsing Techniques
Custom Reviver Function
const jsonString = '{"name": "John", "birthdate": "1994-01-15"}';
const user = JSON.parse(jsonString, (key, value) => {
if (key === 'birthdate') {
return new Date(value);
}
return value;
});
console.log(user.birthdate instanceof Date); // true
console.log(user.birthdate.getFullYear()); // 1994
Handling Large JSON Files
// Streaming JSON parsing for large files
async function parseLargeJson(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Process complete JSON objects
const lines = buffer.split('\n');
buffer = lines.pop(); // Keep incomplete line
for (const line of lines) {
if (line.trim()) {
try {
const item = JSON.parse(line);
processItem(item);
} catch (e) {
// Handle incomplete JSON
}
}
}
}
}
π JSON in Other Languages
JSON parsing and serialization in popular programming languages.
π Python
import json
# Parsing JSON
json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # John
# Serialization
user = {"name": "John", "age": 30}
json_str = json.dumps(user, indent=2)
print(json_str)
# File operations
with open('data.json', 'r') as f:
data = json.load(f)
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
π± Swift (iOS)
import Foundation
// Parsing JSON
let jsonString = """
{"name": "John", "age": 30}
"""
if let jsonData = jsonString.data(using: .utf8) {
do {
let user = try JSONDecoder().decode(User.self, from: jsonData)
print(user.name) // John
} catch {
print("JSON parsing error: \(error)")
}
}
// Serialization
struct User: Codable {
let name: String
let age: Int
}
let user = User(name: "John", age: 30)
do {
let jsonData = try JSONEncoder().encode(user)
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString!) // {"name":"John","age":30}
} catch {
print("JSON encoding error: \(error)")
}
β Java
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
// Parsing JSON
String jsonString = "{\"name\": \"John\", \"age\": 30}";
try {
User user = mapper.readValue(jsonString, User.class);
System.out.println(user.getName()); // John
} catch (Exception e) {
e.printStackTrace();
}
// Serialization
User user = new User("John", 30);
try {
String json = mapper.writeValueAsString(user);
System.out.println(json); // {"name":"John","age":30}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class User {
private String name;
private int age;
// Constructor, getters, setters...
}
JSON Validation and Error Handling
β JSON Validation Techniques
Ensure JSON data integrity and handle parsing errors gracefully.
π‘οΈ Basic Error Handling
Handle JSON parsing errors safely
function safeJsonParse(jsonString) {
try {
const data = JSON.parse(jsonString);
return { success: true, data };
} catch (error) {
return {
success: false,
error: error.message,
position: getErrorPosition(jsonString, error)
};
}
}
function getErrorPosition(jsonString, error) {
// Extract position from error message
const match = error.message.match(/position (\d+)/);
return match ? parseInt(match[1]) : -1;
}
// Usage
const result = safeJsonParse('{"name": "John", "age":}');
if (result.success) {
console.log("Parsed data:", result.data);
} else {
console.error("JSON Error:", result.error);
console.log("Error at position:", result.position);
}
π Schema Validation
Validate JSON structure against a schema
// Simple schema validator
function validateJsonSchema(data, schema) {
const errors = [];
function validateObject(obj, schema, path = '') {
for (const [key, rules] of Object.entries(schema)) {
const value = obj[key];
const currentPath = path ? `${path}.${key}` : key;
if (rules.required && value === undefined) {
errors.push(`${currentPath} is required`);
continue;
}
if (value !== undefined) {
if (rules.type && typeof value !== rules.type) {
errors.push(`${currentPath} must be of type ${rules.type}`);
}
if (rules.minLength && value.length < rules.minLength) {
errors.push(`${currentPath} must be at least ${rules.minLength} characters`);
}
if (rules.pattern && !rules.pattern.test(value)) {
errors.push(`${currentPath} does not match required pattern`);
}
}
}
}
validateObject(data, schema);
return errors;
}
// Usage
const userSchema = {
name: { type: 'string', required: true, minLength: 2 },
email: { type: 'string', required: true, pattern: /^[^@]+@[^@]+$/ },
age: { type: 'number', required: false }
};
const userData = { name: "J", email: "invalid-email" };
const errors = validateJsonSchema(userData, userSchema);
console.log("Validation errors:", errors);
π οΈ JSON Schema Tools
JSON Schema
Standard for JSON validation
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimum": 0
}
},
"required": ["name"]
}
Ajv (Another JSON Schema Validator)
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
},
required: ['name']
};
const validate = ajv.compile(schema);
const data = { name: 'John', age: 30 };
const valid = validate(data);
console.log(valid); // true
π§Ή JSON Sanitization and Security
Protect against malicious JSON data and ensure data safety.
π« Avoid eval() for JSON
// β Dangerous - never do this
const data = eval('(' + jsonString + ')');
// β
Safe - use JSON.parse
const data = JSON.parse(jsonString);
π Input Validation
function sanitizeJsonInput(input) {
// Remove potential script tags
const sanitized = input
.replace(/