jsnotes

Topic 015: JSON Methods (stringify and parse) & localStorage API and in JS

Topic 015: JSON Methods (stringify and parse) & localStorage API and in JS

JavaScript offers powerful tools for storing data on the client side and managing JSON data, including the localStorage API and the JSON.stringify and JSON.parse methods. In this guide, we’ll explore how to use these features effectively to store, retrieve, and manage data in a web application.

1. localStorage API

The localStorage API allows you to store key-value pairs in the browser with no expiration date, meaning data will persist even after the browser is closed. This is ideal for saving user preferences or caching data that you want to keep across sessions.

Frequently Used localStorage Methods

setItem

This method saves a value to localStorage with a unique key.

// Syntax: localStorage.setItem(key, value)
localStorage.setItem("username", "JohnDoe");

getItem

This method retrieves a value by its key.

// Syntax: localStorage.getItem(key)
let username = localStorage.getItem("username");
console.log(username); // Output: JohnDoe

removeItem

The removeItem method deletes a specific item from localStorage by key.

// Syntax: localStorage.removeItem(key)
localStorage.removeItem("username");

clear

This method clears all data stored in localStorage.

// Syntax: localStorage.clear()
localStorage.clear();

Example of using localStorage methods

// Storing user details
localStorage.setItem("username", "JohnDoe");
localStorage.setItem("theme", "dark");

// Retrieving data
console.log(localStorage.getItem("username")); // Output: JohnDoe
console.log(localStorage.getItem("theme")); // Output: dark

// Removing a specific item
localStorage.removeItem("username");

// Clearing all items
localStorage.clear();

2. JSON.stringify Method

The JSON.stringify method converts JavaScript objects or arrays into a JSON string, allowing for easier data storage or transfer. It is often used when storing complex data structures in localStorage or when sending data over HTTP requests.

Example of JSON.stringify

const user = {
  name: "JaneDoe",
  age: 28,
  preferences: {
    theme: "light",
    language: "en",
  },
};

// Convert the user object to a JSON string
const userString = JSON.stringify(user);
console.log(userString);
// Output: {"name":"JaneDoe","age":28,"preferences":{"theme":"light","language":"en"}}

// Storing JSON string in localStorage
localStorage.setItem("user", userString);

3. JSON.parse Method

The JSON.parse method does the opposite of JSON.stringify; it converts a JSON string back into a JavaScript object. This is useful when retrieving JSON-formatted data, such as from localStorage or an API response.

Example of JSON.parse

// Assuming 'user' was previously stored as a JSON string
const userData = localStorage.getItem("user");
const userObj = JSON.parse(userData);
console.log(userObj);
// Output: { name: "JaneDoe", age: 28, preferences: { theme: "light", language: "en" } }

// Accessing properties
console.log(userObj.name); // Output: JaneDoe
console.log(userObj.preferences.theme); // Output: light

Putting It All Together

Here’s a complete example that shows how to save a complex object in localStorage by converting it to a JSON string and retrieve it later by parsing it back into an object.

const settings = {
  notifications: true,
  darkMode: true,
  language: "en",
};

// Convert to JSON string and save to localStorage
localStorage.setItem("settings", JSON.stringify(settings));

// Retrieve and parse back into object
const storedSettings = JSON.parse(localStorage.getItem("settings"));
console.log(storedSettings);
// Output: { notifications: true, darkMode: true, language: "en" }