Storage JSON Handling
Store and retrieve complex objects using JSON
JavaScript Storage JSON Handling Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Store object
const user = {
id: 1,
name: 'John Doe',
email: 'john@example.com',
preferences: {
theme: 'dark',
language: 'en',
notifications: true
},
tags: ['developer', 'javascript']
};
localStorage.setItem('user', JSON.stringify(user));
// Retrieve and parse
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log('User:', storedUser);
// Method 2: Store array
const todos = [
{ id: 1, text: 'Learn JavaScript', completed: false },
{ id: 2, text: 'Build app', completed: true },
{ id: 3, text: 'Deploy', completed: false }
];
localStorage.setItem('todos', JSON.stringify(todos));
const storedTodos = JSON.parse(localStorage.getItem('todos'));
console.log('Todos:', storedTodos);
// Method 3: Update nested object
const userData = JSON.parse(localStorage.getItem('user'));
userData.preferences.theme = 'light';
userData.tags.push('react');
localStorage.setItem('user', JSON.stringify(userData));
// Method 4: Safe get with default
function getStoredData(key, defaultValue = null) {
try {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : defaultValue;
} catch (e) {
console.error('Error parsing stored data:', e);
return defaultValue;
}
}
const settings = getStoredData('settings', { theme: 'light' });
console.log('Settings:', settings);
// Method 5: Storage helper class
class JSONStorage {
static set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (e) {
console.error('Storage error:', e);
return false;
}
}
static get(key, defaultValue = null) {
try {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : defaultValue;
} catch (e) {
console.error('Parse error:', e);
return defaultValue;
}
}
static remove(key) {
localStorage.removeItem(key);
}
static clear() {
localStorage.clear();
}
}
// Usage
JSONStorage.set('config', { apiUrl: 'https://api.example.com', timeout: 5000 });
const config = JSONStorage.get('config');
console.log('Config:', config);
// Method 6: Store with expiration
function setWithExpiry(key, value, ttl) {
const item = {
value: value,
expiry: new Date().getTime() + ttl
};
localStorage.setItem(key, JSON.stringify(item));
}
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
const now = new Date().getTime();
if (now > item.expiry) {
localStorage.removeItem(key);
return null;
}
return item.value;
}
// Store for 1 hour (3600000 ms)
setWithExpiry('token', 'abc123', 3600000);
const token = getWithExpiry('token');
console.log('Token:', token);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: abc123Understanding Storage JSON Handling
JSON enables storing complex data in storage.
JSON Methods
Error Handling
Storage Helpers
Use Cases
Best Practices
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.
Practical Learning Notes for Storage JSON Handling
This JavaScript program is part of the "LocalStorage/SessionStorage" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.