Storage JSON Handling in JavaScript
Store objects and arrays in localStorage with JSON in JavaScript: stringify, parse, safe defaults, a helper class and expiry times. Explanation and output.
Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.
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);
Sample Output
Settings: { theme: 'light' }No settings key existed, so the default was returned.
User: {...}The theme still shows dark because the user was printed before Method 3 changed it.
In this one
- How JSON.stringify and JSON.parse move objects in and out of storage
- How to update nested stored data
- How to read safely with try/catch and defaults
- How to add an expiry time to stored items
How it works
- 1
A user object is saved and read back.
- 2
A todos array is saved and read back.
- 3
The user theme and tags are updated and saved again.
- 4
getStoredData returns a default for missing settings.
- 5
JSONStorage saves and reads config.
- 6
A token is saved with a 1-hour expiry and read back.
Edge cases
Broken JSON
JSON.parse('{bad') throws a SyntaxError.
Wrap parse in try/catch and return a default.
Dates
A Date comes back as a string.
Convert it with new Date(value) after parsing.
Expired item
getWithExpiry returns null and deletes the key.
Handle null as "need to fetch again".
What's going on
Browser storage only holds strings. Real apps need objects and arrays, like a user profile or a to-do list. JSON is the bridge. JSON.stringify() converts a value to a string. JSON.parse() converts the string back. It handles objects, arrays and nested data.
Method 1 saves a user object with nested preferences and a tags array, then reads it back whole. Method 2 does the same for an array of to-do items.
Method 3 updates nested data. You cannot change one property inside storage directly. You read the whole object, parse it, change it, and save it again. Here the theme becomes light and a tag is added. This is a read, change, write cycle.
Things can go wrong. A key may be missing, or the stored text may be broken, for example after a manual edit. JSON.parse throws an error on bad text. Method 4 wraps the read in try/catch and returns a default value instead. Since "settings" was never saved, it returns { theme: 'light' }.
Method 5 puts this logic in a JSONStorage class with set, get, remove and clear. Helpers like this keep error handling in one place, provide defaults, and make it easy to add features.
Method 6 adds expiry, a feature storage does not have. It saves an object with the value and an expiry time. TTL means time to live, here 3600000 milliseconds, one hour. On read, if the time has passed, the item is removed and null is returned.
Some values do not survive JSON. Dates become strings, and functions and undefined are dropped. Best practices: always use try/catch, provide default values, validate parsed data, and handle storage errors.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does JSON.stringify({a: 1}) return?
Pick an answer to check it.
Question 2
What does JSON.parse throw on invalid text?
Pick an answer to check it.
Questions people ask
Why not store the object directly?
Storage would call toString and save "[object Object]".
Is JSON.parse slow on big data?
It is fast, but huge values block the page. Keep stored data small.
Can I store Map or Set?
Not directly. Convert them to arrays first.