Home >Web Front-end >JS Tutorial >How Can I Store Non-String Data in HTML5 LocalStorage/SessionStorage?

How Can I Store Non-String Data in HTML5 LocalStorage/SessionStorage?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-22 14:41:11620browse

How Can I Store Non-String Data in HTML5 LocalStorage/SessionStorage?

How to Store Non-Strings in HTML5 LocalStorage/SessionStorage

In contrast to primitive types and arrays, storing JavaScript objects directly in HTML5 storage results in their conversion to strings. This limitation has been a topic of debate, leading to confusion among developers.

According to the HTML5 Web Storage specification, the setItem() method expects key/value pairs to be strings. To overcome this limitation, consider the following workaround:

JSON Serialization and Deserialization

To store an object in HTML5 storage, convert it to a JSON string using JSON.stringify(). Upon retrieval, parse the JSON string back into an object using JSON.parse().

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));

console.log('Retrieved object:', retrievedObject);

Example Output:

Retrieved object: { one: 1, two: 2, three: 3 }

By serializing the object before storage and deserializing it after retrieval, you can effectively store and retrieve JavaScript objects in HTML5 storage.

The above is the detailed content of How Can I Store Non-String Data in HTML5 LocalStorage/SessionStorage?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn