Summary - JSON
Write a function that saves and reloads a settings object using JSON.stringify and JSON.parse.
Summary - Data format
In this group you learned to turn objects into text and text back into objects. stringify turns an object into text, parse turns text into an object. structuredClone produces an independent deep copy.
Remember: handle undefined, functions and Date with care; the format does not support them directly. Now you will write a function that saves and reloads a settings object.
Exercise Save the settings as text
Turn the settings object into text and save it to localStorage under the 'settings' key. Use the stringify method.
Show example solution
Turn into text with stringify, save with localStorage.setItem.
Example solution:
localStorage.setItem('settings', stringify(settings));
Exercise Reload the saved settings
Read the text from localStorage under the 'settings' key, turn it into an object with parse and assign it to loaded.
Show example solution
Read with getItem, turn into an object with parse.
Example solution:
const loaded = parse(localStorage.getItem('settings'));
Test yourself
-
Which method to save settings?
- stringify
- parse
- structuredClone
- trim
Show answer
stringify — Correct! stringify turns the object into text for storage.
-
Match the methods
- stringify
- object to text
- parse
- text to object
- structuredClone
- deep copy
- setItem
- writes to storage