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 object
2const user = {
3 id: 1,
4 name: 'John Doe',
5 email: 'john@example.com',
6 preferences: {
7 theme: 'dark',
8 language: 'en',
9 notifications: true
10 },
11 tags: ['developer', 'javascript']
12};
13
14localStorage.setItem('user', JSON.stringify(user));
15
16// Retrieve and parse
17const storedUser = JSON.parse(localStorage.getItem('user'));
18console.log('User:', storedUser);
19
20// Method 2: Store array
21const 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];
26
27localStorage.setItem('todos', JSON.stringify(todos));
28
29const storedTodos = JSON.parse(localStorage.getItem('todos'));
30console.log('Todos:', storedTodos);
31
32// Method 3: Update nested object
33const userData = JSON.parse(localStorage.getItem('user'));
34userData.preferences.theme = 'light';
35userData.tags.push('react');
36localStorage.setItem('user', JSON.stringify(userData));
37
38// Method 4: Safe get with default
39function 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}
48
49const settings = getStoredData('settings', { theme: 'light' });
50console.log('Settings:', settings);
51
52// Method 5: Storage helper class
53class 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 }
63
64 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 }
73
74 static remove(key) {
75 localStorage.removeItem(key);
76 }
77
78 static clear() {
79 localStorage.clear();
80 }
81}
82
83// Usage
84JSONStorage.set('config', { apiUrl: 'https://api.example.com', timeout: 5000 });
85const config = JSONStorage.get('config');
86console.log('Config:', config);
87
88// Method 6: Store with expiration
89function setWithExpiry(key, value, ttl) {
90 const item = {
91 value: value,
92 expiry: new Date().getTime() + ttl
93 };
94 localStorage.setItem(key, JSON.stringify(item));
95}
96
97function getWithExpiry(key) {
98 const itemStr = localStorage.getItem(key);
99 if (!itemStr) return null;
100
101 const item = JSON.parse(itemStr);
102 const now = new Date().getTime();
103
104 if (now > item.expiry) {
105 localStorage.removeItem(key);
106 return null;
107 }
108
109 return item.value;
110}
111
112// 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: abc123

What'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