JSON and localStorage
Learning Goals
- Understand the difference between server-side and client-side storage
- Understand and utilize localStorage
- Understand and utilize JSON
- Understand when and why one would use
data-
attributes
Vocabulary
Client-side Storage
Storage on the client (usually the browser)Server-side storage
Storage on the serverlocalStorage
An implementation of Client-side StorageJSON
(JavaScript Object Notation) is a lightweight data-interchange formatdata-
attributes, a way of storing information related to the data model on an html element
Client-side vs. Server-side Storage
Up until this point, the data in our projects has disappeared whenever we refresh our page, which is problematic. It would be nice if we could keep our ideas on the page without having to recreate them every time we want to see our CSS changes. There are two places we could store our data to make that happen.
There are two primary ways of storing data in web applications, which are - server-side and client-side.
Server-side storage: On someone else’s computer (often times one that is in a data warehouse), in a database. Good for storing sensitive information.
Client-side storage: On the user’s computer, using a JavaScript API (Most commonly the web storage API). Good for storing less sensitive information (ie. a shopping cart).
Your turn With a partner, come up with an analogies for server-side and client-side storage.
Client-side Storage
Browsers provide two main types of immediate storage that is accessible without messing with a database: sessionStorage
which gets reset whenever your browser session restarts, and localStorage
, which has no specified expiration date. Today we will strictly be talking about localStorage
.
The web storage API is a secure way your browser can store key value pairs that are unique to each domain. So, if you store some information on a page hosted at github.com
, then it is not accessible from a page hosted at twitter.com
. This is for security reasons as well as to guarantee that the pages won’t end up with conflicting names and overwriting items in storage from another site.
Local Storage
localStorage
is a property you can call on the global window
variable within your browser, just like you can call document
, that allows you to access a local storage object for persisting data.
localStorage
supports the following methods:
localStorage.setItem();
takes two arguments—a key and value (key must be string)—and stores the given value under the provided key.localStorage.getItem();
gets an item from storage based on the key provided.localStorage.removeItem();
takes a key and removes that key and its associated value from storage.localStorage.clear();
removes all items from storage for that domain.
Your Turn
Open up the developer tools on this page and try the following:
localStorage.setItem('storeMePlease', 2);
localStorage.getItem('storeMePlease');
- Refresh the page and try to get the item again.
localStorage.removeItem('storeMePlease');
localStorage.getItem('storeMePlease');
localStorage.setItem('anotherThing', 'you look nice today');
localStorage.getItem('anotherThing');
localStorage.clear();
localStorage.setItem('somethingComplicated', { crust: 'deep dish', type: 'veggie' });
localStorage.getItem('somethingComplicated');
What are your observations?
Check out the docs. What other methods are available to you when using localStorage?
localStorage in Action
How can we improve the functionality of the following CodePen with local storage?
See the Pen localStorage in Action - Save Info Form by Turing School (@turing-school) on CodePen.
What is JSON?
When we’re communicating with servers, we use a transport protocol called HTTP.
HTTP powers the web, but it does have one limitation. All information can only be sent back and forth using strings. Strings are great, but it’s not hard to imagine a world where we might want to send slightly more complicated data structures back (e.g. objects and arrays) back and forth between the client and the server.
JSON stands for “JavaScript Object Notation” and is an alternative to XML as a standard for sending information back and forth over the web. It’s a subset of JavaScript’s object syntax. JSON is a language-independent data format that is easy for humans to read and write and easy for machines to parse and generate.
JSON has the following rules:
- Keys must be double quoted.
- Values must be one of the following types:
- Strings, double quoted
- Numbers
- Booleans
- Arrays
- Objects
- Keys can only be properties, not methods
- Therefore, values cannot be functions
JSON is a means of sending data.
The browser provides a JSON
object with two methods.
JSON.stringify();
turns any JavaScript object into valid JSON.JSON.parse();
turns any valid JSON into a JavaScript object.
Your Turn
Take the object from the previous exercise that didn’t work and refactor it. Don’t look below quite yet…
- You should use
JSON.stringify();
before storing it inlocalStorage
. - You should use
JSON.parse();
after retrieving it fromlocalStorage
.
Complete Workflow in Console
The goal is to take our object, store it in local storage, and then be able to take the object out of local storage and modify the object.
var objectToStore = { crust: 'deep dish', type: 'veggie' };
var stringifiedObject = JSON.stringify(objectToStore);
stringifiedObject
(Notice our object has turned into a string!)localStorage.setItem('somethingComplicated', stringifiedObject);
(Stores the object in local storage)
Now the object is in local storage, and we can retrieve it out of local storage.
var retrievedObject = localStorage.getItem('somethingComplicated');
retrievedObject
(Notice this is still the stringified version of our object - we need it to be a real object again, not a string)var parsedObject = JSON.parse(retrievedObject);
parsedObject
(We are now back to our original object!)
JSON in Action
See the Pen JSON in Action - Contact Form by Turing School (@turing-school) on CodePen.
Data Attributes
In addition to giving our html elements id
and class
attributes, sometimes it may be more appropriate to give our elements a data-
attribute instead.
data-
attributes are used to store information related to the data of the content your showing.
For instance, if you have a lot of objects of the same type and they are all represented on the web page the same way, then you can use a data-
attribute to identify them via the dom.
Here we can see an html example of using a data-
attribute on an element. Note that whatever comes after the -
is totally up to the developer.
<article data-name="cookie"></article>
And now in our JavaScript we can access that article using it’s data attribute.
var article = document.querySelector('article');
article.dataset.name // "cookie"
The js and jquery docs are both great and more easy to read than most when it comes to data-
attributes. They are linked in the dig deeper section below.
Storage Events
Whenever you change a value in localStorage, the DOM will fire a storage
event in every other page currently open on that domain.
Open this CodePen up in two different windows to see.