Answer: Use the JSON.stringify()
Method
Local Storage or Session Storage can only store strings key/value pairs by default. The web storage can be used to store JavaScript objects. However, this trick is not necessary.
To store objects, stringify them by using JSON.stringify()
and then parse with JSON.parse()
whenever you need to retrieve them, as shown in this example:
<script>
var personObject = { name: "Peter", age: 18, married: false };
// Convert the person object into JSON string and save it into storage
localStorage.setItem("personObject", JSON.stringify(personObject));
// Retrieve the JSON string
var jsonString = localStorage.getItem("personObject");
// Parse the JSON string back to JS object
var retrievedObject = JSON.parse(jsonString);
console.log(retrievedObject);
// Accessing individual values
console.log(retrievedObject.name); // Prints: Peter
console.log(retrievedObject.age); // Prints: 18
console.log(retrievedObject.married); // Prints: false
</script>
You can learn more about both local and session storage by visiting the HTML 5 web storage tutorial.