Storage JSON Handling

Store and retrieve complex objects using JSON

JavaScriptIntermediate
JavaScript
// Method 1: Store object
const user = {
    id: 1,
    name: 'John Doe',
    email: '[email protected]',
    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);

Output

User: { id: 1, name: 'John Doe', email: '[email protected]', 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

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