Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateJavaScript LocalStorage and SessionStorageExample 4 of 10

Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.

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);

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. 1

    A user object is saved and read back.

  2. 2

    A todos array is saved and read back.

  3. 3

    The user theme and tags are updated and saved again.

  4. 4

    getStoredData returns a default for missing settings.

  5. 5

    JSONStorage saves and reads config.

  6. 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.