Storage JSON Handling in JavaScript
Store and retrieve complex objects using JSON
IntermediateLocalStorage/SessionStorageExample 4 of 10
storage-json-handling.js
1// Method 1: Store object2const user = {3 id: 1,4 name: 'John Doe',5 email: 'john@example.com',6 preferences: {7 theme: 'dark',8 language: 'en',9 notifications: true10 },11 tags: ['developer', 'javascript']12};1314localStorage.setItem('user', JSON.stringify(user));1516// Retrieve and parse17const storedUser = JSON.parse(localStorage.getItem('user'));18console.log('User:', storedUser);1920// Method 2: Store array21const todos = [22 { id: 1, text: 'Learn JavaScript', completed: false },23 { id: 2, text: 'Build app', completed: true },24 { id: 3, text: 'Deploy', completed: false }25];2627localStorage.setItem('todos', JSON.stringify(todos));2829const storedTodos = JSON.parse(localStorage.getItem('todos'));30console.log('Todos:', storedTodos);3132// Method 3: Update nested object33const userData = JSON.parse(localStorage.getItem('user'));34userData.preferences.theme = 'light';35userData.tags.push('react');36localStorage.setItem('user', JSON.stringify(userData));3738// Method 4: Safe get with default39function getStoredData(key, defaultValue = null) {40 try {41 const data = localStorage.getItem(key);42 return data ? JSON.parse(data) : defaultValue;43 } catch (e) {44 console.error('Error parsing stored data:', e);45 return defaultValue;46 }47}4849const settings = getStoredData('settings', { theme: 'light' });50console.log('Settings:', settings);5152// Method 5: Storage helper class53class JSONStorage {54 static set(key, value) {55 try {56 localStorage.setItem(key, JSON.stringify(value));57 return true;58 } catch (e) {59 console.error('Storage error:', e);60 return false;61 }62 }6364 static get(key, defaultValue = null) {65 try {66 const data = localStorage.getItem(key);67 return data ? JSON.parse(data) : defaultValue;68 } catch (e) {69 console.error('Parse error:', e);70 return defaultValue;71 }72 }7374 static remove(key) {75 localStorage.removeItem(key);76 }7778 static clear() {79 localStorage.clear();80 }81}8283// Usage84JSONStorage.set('config', { apiUrl: 'https://api.example.com', timeout: 5000 });85const config = JSONStorage.get('config');86console.log('Config:', config);8788// Method 6: Store with expiration89function setWithExpiry(key, value, ttl) {90 const item = {91 value: value,92 expiry: new Date().getTime() + ttl93 };94 localStorage.setItem(key, JSON.stringify(item));95}9697function getWithExpiry(key) {98 const itemStr = localStorage.getItem(key);99 if (!itemStr) return null;100101 const item = JSON.parse(itemStr);102 const now = new Date().getTime();103104 if (now > item.expiry) {105 localStorage.removeItem(key);106 return null;107 }108109 return item.value;110}111112// Store for 1 hour (3600000 ms)113setWithExpiry('token', 'abc123', 3600000);114const token = getWithExpiry('token');115console.log('Token:', token);
Output
User: { id: 1, name: 'John Doe', email: 'john@example.com', preferences: { theme: 'dark', language: 'en', notifications: true }, tags: ['developer', 'javascript'] }
Todos: [
{ id: 1, text: 'Learn JavaScript', completed: false },
{ id: 2, text: 'Build app', completed: true },
{ id: 3, text: 'Deploy', completed: false }
]
Settings: { theme: 'light' }
Config: { apiUrl: 'https://api.example.com', timeout: 5000 }
Token: abc123What's going on
JSON enables storing complex data in storage.
JSON Methods
JSON.stringify(): Convert to string
JSON.parse(): Convert from string
Handles objects, arrays, nested data
Error Handling
Use try-catch
Provide defaults
Validate data
Storage Helpers
Encapsulate logic
Handle errors
Provide defaults
Add features (expiry, etc.)
Use Cases
User preferences
Application state
Cached data
Form data
Best Practices
Always use try-catch
Provide default values
Validate parsed data
Handle storage errors