Advanced Local Storage Techniques: Applying the Power of JSON with Examples #2

Local storage is an important feature of web development because it allows users to store data locally within their browsers. It provides a smooth browsing experience by retaining user data across sessions, improving performance, and decreasing the need for frequent server queries. JSON (JavaScript Object Notation) is a versatile and efficient storage format that is easy to read and compatible with JavaScript. Using JSON in sophisticated local storage techniques can greatly improve data management, retrieval, and manipulation in online applications.

Understanding JSON

JSON, a lightweight data transfer format, is widely used in web development due to its simplicity and versatility. Data is represented in a structured style utilizing key-value pairs, arrays, and nested structures, making it extremely understandable for both humans and machines. JavaScript’s native support for JSON facilitates data manipulation and allows for easy integration with local storage systems.

Syntax

JSON syntax is simple for developers who are familiar with JavaScript to understand because it is based on JavaScript object notation. Enclosed in square brackets [] for arrays and curly braces {} for objects, it contains data. There are colons between each key-value pair and commas between each individual element.

Data Types

JSON supports a variety of data types, including strings, numbers, booleans, arrays, objects, and nulls. JSON’s flexibility enables it to express a diverse range of data structures, from simple values to sophisticated data hierarchies.

Objects and Arrays

JSON objects are collections of key-value pairs, where the keys are strings and the values can be any JSON type. Arrays are ordered lists of values that enable the storage of several things in a single variable.

Parsing and Serialization

JSON parsing converts a JSON string into a native data structure, such a JavaScript object, whereas serialization converts a native data structure back into a JSON string. These processes are necessary for sharing data between systems or platforms.

Usage

JSON is widely used in web development for activities like as transmitting data between a client and server via AJAX (Asynchronous JavaScript and XML) requests, storing configuration settings, and exchanging data through APIs.

Advanced Local Storage Techniques with JSON

Structured Data Storage

JSON defines a standardized format for storing many forms of data, such as characters, numbers, arrays, and objects. Developers can use JSON’s hierarchical structure to organize data into logical entities, allowing for more efficient retrieval and manipulation. For example, user preferences, settings, and application state can be saved as JSON objects in local storage, assuring data consistency and clarity.

Serialization and Deserialization

Serialization is the conversion of complicated data structures like objects or arrays into a JSON string for storage. Deserialization is the process of recovering the original data from a JSON string. JSON.stringify() and JSON.parse() are built-in JavaScript functions that allow for easy serialization and deserialization, respectively. These technologies allow developers to easily store and retrieve complicated data structures, maximizing storage efficiency while maintaining data integrity.

Partial Data Updates

JSON’s hierarchical structure enables targeted modifications to individual data fields within stored objects. Instead of overwriting the entire object, developers can change individual properties, reducing data transport and storage cost. This technique is especially effective in instances when only some aspects of an object must be modified, such as user profiles or application configurations.

Querying and Filtering

JSON’s flexible structure allows for rapid querying and filtering of data stored locally. Developers can use JavaScript array methods like filter(), map(), and reduce() to execute complex JSON operations like searching, sorting, or aggregating depending on certain criteria. This enables dynamic data manipulation and presentation in online applications, which improves user experience and engagement.

Data Compression and Encryption

To improve storage efficiency and data security, developers can use techniques like data compression and encryption in conjunction with JSON-based local storage. Compression methods like as gzip or deflate can considerably reduce the size of JSON strings, reducing storage and bandwidth use. Furthermore, encrypting important data within JSON payloads assures confidentiality and integrity, preventing unauthorized access and modification.

Offline Data Synchronization

JSON-based local storage allows for easy offline data synchronization in web applications. Applications can operate offline by saving JSON representations of data entities locally and synchronizing changes with remote servers when they reconnect. Techniques like as differential synchronization and conflict resolution techniques allow for rapid updates to distributed data storage, maintaining consistency and reliability across devices and platforms.

Understanding JSON.stringify and JSON.parse in Local Storage

JSON.stringify and JSON.parse are two crucial techniques for storing and retrieving structured data in local storage. Here, we’ll look at JSON.stringify and JSON.parse, how they work with local storage, and how to use them in practice.

JSON.stringify()

JSON.stringify() is a JavaScript function that turns a JavaScript object or value into a JSON string. This strategy is frequently used for saving data locally to maintain compatibility and consistency across multiple platforms and environments.

Syntax

JavaScript
JSON.stringify(value);

Example

JavaScript
const data = { name: 'Bob', age: 26 };
const jsonString = JSON.stringify(data);

In this example, the object data is converted into a JSON string jsonString, which can then be stored in local storage.

JSON.parse()

JSON.parse() is a JavaScript method that parses a JSON string and creates the JavaScript value or object represented by the string. When getting data from local storage, this function converts the stored JSON string back to its original JavaScript object or value.

Syntax

JavaScript
JSON.parse(jsonString);

Example

JavaScript
const jsonString = '{"name": "Kate", "age": 32}';
const data = JSON.parse(jsonString);

In this example, the JSON string jsonString is parsed back into the original object data, which can then be used in JavaScript code.

Using JSON.stringify and JSON.parse with Local Storage

Developers can save data locally in the user’s browser thanks to local storage. Data integrity and compatibility can be ensured by developers storing structured data, such as objects and arrays, locally while utilizing JSON.stringify and JSON.parse.

Storing Data in Local Storage

JavaScript
const data = { name: 'John', age: 30 };
localStorage.setItem('userData', JSON.stringify(data));

Retrieving Data from Local Storage

JavaScript
const jsonString = localStorage.getItem('userData');
const userData = JSON.parse(jsonString);

Let’s walk through some simple examples to illustrate the usage of JSON.stringify() and JSON.parse() with local storage.

Example 1: Storing and Retrieving a JavaScript Object in Local Storage

JavaScript
// Create a JavaScript object
const person = {
  name: 'Rose',
  age: 30,
  city: 'Birmingham'
};

// Convert the object to a JSON string and store it in local storage
localStorage.setItem('personData', JSON.stringify(person));

// Retrieve the JSON string from local storage and parse it back to an object
const storedData = localStorage.getItem('personData');
const parsedData = JSON.parse(storedData);

// Output the retrieved object
console.log(parsedData); // Output: { name: ' Rose ', age: 22, city: ' Birmingham' }

In this example:

  • We create a JavaScript object person with properties like name, age, and city.
  • We use JSON.stringify(person) to convert the object to a JSON string.
  • The JSON string is stored in local storage with the key ‘personData’.
  • We retrieve the JSON string from local storage using localStorage.getItem(‘personData’).
  • We use JSON.parse() to convert the JSON string back into a JavaScript object, parsedData.

Example 2: Storing and Retrieving an Array of Objects in Local Storage

JavaScript
// Create an array of objects
const students = [
  { name: 'John', age: 21 },
  { name: 'Rose', age: 22 },
  { name: 'Kate', age: 23 }
];

// Convert the array to a JSON string and store it in local storage
localStorage.setItem('studentData', JSON.stringify(students));

// Retrieve the JSON string from local storage and parse it back to an array of objects
const storedData = localStorage.getItem('studentData');
const parsedData = JSON.parse(storedData);

// Output the retrieved array of objects
console.log(parsedData);

/*
Output in console :

(3) [{…}, {…}, {…}]
0: {name: 'John', age: 21}
1: {name: 'Rose', age: 22}
2: {name: 'Kate', age: 23}
length: 3
[[Prototype]]: Array(0)

*/

In this example:

  • We create an array of objects students.
  • We use JSON.stringify(students) to convert the array to a JSON string.
  • The JSON string is stored in local storage with the key ‘studentData’.
  • We retrieve the JSON string from local storage using localStorage.getItem(‘studentData’).
  • We use JSON.parse() to convert the JSON string back into an array of objects, parsedData.

These examples show how JSON.stringify() and JSON.parse() can be combined with local storage to store and retrieve structured data in web applications. Developers can successfully manage and store data between browser sessions by transforming JavaScript objects/values to JSON strings before saving them locally, and then parsing them back into JavaScript objects/values after retrieval.

Handling Data Types and Event Handling in Web Storage API

Handling Data Types in Web Storage API

1. Storing and Retrieving Strings

How to store a string in localStorage and retrieve it.

JavaScript
localStorage.setItem('message', 'Hello, world!');
const message = localStorage.getItem('message');
console.log(message); // Output: Hello, world!

2. Storing and Retrieving Numbers

How to store a number in localStorage and retrieve it.

JavaScript
localStorage.setItem('count', 42);
const count = parseInt(localStorage.getItem('count'));
console.log(count); // Output: 42

3. Storing and Retrieving Boolean Values

How to store a boolean value in localStorage and retrieve it.

JavaScript
localStorage.setItem('isLogged', true);
const isLoggedIn = JSON.parse(localStorage.getItem('isLogged'));
console.log(isLoggedIn); // Output: true

4. Storing and Retrieving Arrays

How to store an Array in localStorage and retrieve it.

JavaScript
const data = ['apple', 'banana', 'orange'];
localStorage.setItem('fruits', JSON.stringify(data));
const storedData = JSON.parse(localStorage.getItem('fruits'));
console.log(storedData); // Output: ['apple', 'banana', 'orange']

5. Storing and Retrieving Objects

How to store an Object in localStorage and retrieve it.

JavaScript
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log(storedUser); // Output: { name: 'John', age: 30 }

Event Handling in Web Storage API

1. Detecting Changes in Storage

Detect when localStorage data changes.

JavaScript
window.addEventListener('storage', function(event) {
    console.log('Storage changed:', event.key, event.newValue);
});

Example – Easy localStorage Change Detection for Beginners

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>localStorage Change Detection</title>
</head>
<body>
<h1>localStorage Change Detection Example</h1>

<button onclick="updateLocalStorage()">Update localStorage</button>

<script>
// Function to update localStorage data
function updateLocalStorage() {
    // Generate a random number to update data
    var randomNumber = Math.floor(Math.random() * 100);
    
    // Update the data in localStorage
    localStorage.setItem('exampleData', randomNumber);
    
    // Log the update to the console
    console.log('localStorage updated with:', randomNumber);
}

// Event listener to detect changes in localStorage
window.addEventListener('storage', function(event) {
    if (event.key === 'exampleData') {
        console.log('localStorage changed:', event.key, event.newValue);
    }
});
</script>

<!------Output will be like this when you click on Update storage button ------->
<!------------
localStorage updated with: 9
localStorage updated with: 52
localStorage updated with: 68
localStorage updated with: 64
--------->
</body>
</html>

Explanation :

  • This HTML document contains a button labeled “Update localStorage”.
  • When the button is clicked, the updateLocalStorage() function is triggered.
  • The updateLocalStorage() function generates a random number and stores it in localStorage with the key ‘exampleData’.
  • It also logs the updated data to the console.
  • There’s an event listener attached to the window object that listens for changes in localStorage.
  • When a change is detected, it checks if the changed key matches ‘exampleData’. If it does, it logs the change to the console and displays an alert with the updated value.

To use this example

  • Copy the code into an HTML file.
  • Open the HTML file in a web browser.
  • Click the “Update localStorage” button to update the stored data.
  • Check the browser console for logged messages indicating changes in localStorage.

2. Syncing Data Between Tabs

Keep data synchronized between multiple browser tabs.

JavaScript
window.addEventListener('storage', function(event) {
    if (event.key === 'sharedData') {
        console.log('Data synced between tabs:', event.newValue);
    }
});

Example – Easy Data Sync Between Browser Tabs Using localStorage

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Syncing Data Between Tabs </title>
</head>

<body>
    <h1>Syncing Data Between Tabs </h1>

    <!-- Input field to update shared data -->
    <label for="dataInput">Enter Data Here:</label>
    <input type="text" id="dataInput">
    <button onclick="updateSharedData()">Update Data</button>

    <script>
        // Function to update shared data in localStorage
        function updateSharedData() {
            var newData = document.getElementById('dataInput').value;
            localStorage.setItem('sharedData', newData);
            console.log('Data updated:', newData);
        }

        // Event listener to detect changes in localStorage
        window.addEventListener('storage', function (event) {
            if (event.key === 'sharedData') {
                console.log('Data synced between tabs:', event.newValue);
                // Update UI with synced data
                document.getElementById('dataInput').value = event.newValue;
            }
        });
    </script>

</body>

</html>

Explanation :

  • This HTML document includes an input field (dataInput) and a button labeled “Update Data”.
  • When the “Update Data” button is clicked, the updateSharedData() function is triggered.
  • The updateSharedData() function retrieves the value entered in the input field (dataInput), stores it in localStorage with the key ‘sharedData’, and logs the updated data to the console.
  • There’s an event listener attached to the window object that listens for changes in localStorage.
  • When a change is detected in localStorage, the event listener checks if the changed key matches ‘sharedData’. If it does, it logs the synced data to the console and updates the UI by setting the value of the input field (dataInput) to the synced data.

To use this example :

  • Copy the code into an HTML file.
  • Open the HTML file in a web browser.
  • Open more than one tab on browser and open this HTML file in all opened tabs with console open.
  • Enter some data into the input field and click the “Update Data” button.
  • Open another tab in the same browser and observe that the entered data is synced between tabs automatically. Any changes made in one tab will be reflected in all other tabs.

3. Clearing Storage on Logout

Clear localStorage when the user logs out

JavaScript
localStorage.removeItem('accessToken');
localStorage.clear(); // Optional: Clear all stored data

Example – Simple Login and Logout with localStorage

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login and Logout </title>
</head>

<body>
    <h1>Login and Logout </h1>
    <p>Add username : admin and password : 12345 to login</p>

    <div id="loginForm">
        <h2>Login</h2>
        <label for="username">Username:</label>
        <input type="text" id="username">
        <label for="password">Password:</label>
        <input type="password" id="password">
        <button onclick="login()">Login</button>
    </div>

    <div id="userInfo" style="display: none;">
        <h2>User Info</h2>
        <p>Welcome, <span id="loggedInUser"></span>!</p>
        <button onclick="logout()">Logout</button>
    </div>

    <script>
        // Function to perform login
        function login() {
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;

            // Check login credentials (dummy validation)
            if (username === 'admin' && password === '12345') {
                // Set user info in localStorage
                localStorage.setItem('loggedInUser', username);

                // Display user info section
                document.getElementById('loginForm').style.display = 'none';
                document.getElementById('userInfo').style.display = 'block';
                document.getElementById('loggedInUser').innerText = username;

                console.log('Logged in as:', username);
            } else {
                alert('Invalid username or password. Please try again.');
            }
        }

        // Function to perform logout
        function logout() {
            // Clear localStorage on logout
            localStorage.removeItem('loggedInUser');

            // Hide user info section and display login form
            document.getElementById('userInfo').style.display = 'none';
            document.getElementById('loginForm').style.display = 'block';

            console.log('Logged out: localStorage cleared');
            alert('Logged out successfully!');
        }

        // Check if user is already logged in
        document.addEventListener('DOMContentLoaded', function () {
            var loggedInUser = localStorage.getItem('loggedInUser');
            if (loggedInUser) {
                // Display user info section with logged-in user details
                document.getElementById('loginForm').style.display = 'none';
                document.getElementById('userInfo').style.display = 'block';
                document.getElementById('loggedInUser').innerText = loggedInUser;
            }
        });
    </script>

</body>

</html>

Explanation :

  • This HTML document contains two sections: one for the login form (loginForm) and another for displaying user information (userInfo).
  • The login form includes input fields for username and password, along with a login button. The user enters their credentials to log in.
  • The login() function validates the entered credentials (dummy validation for demonstration purposes) and sets the logged-in user’s information in localStorage upon successful login.
  • The logout() function clears the user’s information from localStorage upon logout and hides the user info section while displaying the login form again.
  • When the page loads (DOMContentLoaded event), it checks if a user is already logged in by checking localStorage. If a user is logged in, it displays the user info section with the logged-in user’s details.
  • Alerts are shown to provide feedback to the user upon successful login/logout.

To use this example :

  • Copy the code into an HTML file.
  • Open the HTML file in a web browser.
  • Enter the username “admin” and password “12345” to log in. On successful login, you’ll see a welcome message with the logged-in user’s name (admin).
  • Click the “Logout” button to log out. You’ll see an alert confirming successful logout, and the login form will be displayed again.

4. Handling Quota Exceeded Error

Handle the error when localStorage quota is exceeded.

JavaScript
try {
    localStorage.setItem('largeData', '...');
} catch (error) {
    console.error('Local storage quota exceeded:', error);
}

Example – how to handle errors when the localStorage quota is exceeded :

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Handling localStorage Quota Exceeded Error </title>
</head>
<body>
<h1>Handling localStorage Quota Exceeded Error </h1>

<button onclick="storeData()">Store Large Data</button>

<script>
// Function to store large data in localStorage
function storeData() {
    try {
        // Attempt to store large data in localStorage
        localStorage.setItem('largeData', generateLargeData());
        console.log('Large data stored successfully.');
    } catch (error) {
        console.error('Local storage quota exceeded:', error);
        alert('Failed to store large data: Local storage quota exceeded.');
    }
}

// Function to generate large data (dummy function for demonstration)
function generateLargeData() {
    // Generate a large string of data (e.g., 5MB)
    var largeData = '';
    for (var i = 0; i < 5000000; i++) {
        largeData += 'A'; // Append character 'A' repeatedly
    }
    return largeData;
}
</script>

</body>
</html>

Explanation :

  • This HTML document contains a button labeled “Store Large Data”.
  • When the button is clicked, the storeData() function is triggered.
  • Inside the storeData() function, we attempt to store large data in localStorage using localStorage.setItem(‘largeData’, generateLargeData()).
  • We wrap the localStorage.setItem() operation inside a try-catch block to handle any errors that may occur.
  • If the localStorage quota is exceeded, an error will be caught in the catch block. We log the error message to the console that storing large data failed due to the localStorage quota being exceeded.
  • The generateLargeData() function is a dummy function used to generate a large string of data (5MB in this example) for demonstration purposes.

To use this Example :

  • Copy the code into an HTML file.
  • Open the HTML file in a web browser.
  • Click the “Store Large Data” button to attempt to store large data in localStorage. If the localStorage quota is exceeded, an error will be logged to the console.

Conclusion

Throughout this study, we discovered how JSON serialization improves data management, persistence, and efficiency in online applications. By leveraging JSON’s flexibility and compatibility, developers can open up a plethora of options for storing and processing structured data locally. From serialization methodologies to integration techniques, this blog post has demonstrated the revolutionary impact of mixing JSON with local storage. As technology advances, understanding these advanced strategies will surely enable developers to construct more dynamic, responsive, and efficient online applications. So, let us embrace the power of JSON and go on a voyage of innovation and optimization in local storage techniques.

Basic of Web Storage – Web Storage API Essentials: Everything You Need to Know to Get Started – #1

Local Storage Practical Examples : Mastering Local Storage in Web Development: 8 Practical Examples, From Novice to Expert! #3

CSSHTMLJavascriptWeb Storage

Recent Blogs

Web Storage API Essentials: Everything You Need to Know to Get Started – #1

Web Storage API Essentials – In today’s web development market, effective client-side data management is critical for providing seamless user experiences.

CSSHTMLJavascriptWeb Storage

Ready to Maximize Your Design Potential? : Illustrator’s Variable Helps You to Automate 100s of Unique Designs

Illustrator’s Variable – Variables in Adobe Illustrator offer a powerful way to streamline design workflows, especially for projects with repetitive elements or variable data. Whether you’re creating personalized invitations, data-driven infographics, or dynamic packaging designs, mastering variables can significantly enhance your efficiency and productivity. In this step-by-step guide, we’ll explore how to harness the full potential of variables in Illustrator.

Graphic DesignIllustrator

Understanding CSS Progress Bars: A Comprehensive Guide #1

In the world of web development, having a visually appealing and user-friendly interface is essential. The progress bar is a vital aspect of reaching this goal. Progress bars not only give users a sense of readiness and feedback, but they also enhance the overall user experience. Although there are various ways to implement progress bars, CSS […]

CSSHTMLWeb design

12 Essential Design Principles Explained: Your Comprehensive Manual

Design principles are basic ideas and rules that direct the process of creating visually beautiful, useful, and efficient designs in a variety of fields

Design PrinciplesUi Design