Skip to content

Prep 11: Data Persistence

Textbook Reading

Activity: Save and Load

In this activity, you’ll explore saving and loading files from JavaScript!

We’ve created a simple meal tracker application. Your job is to make it be able to save and load its data using JSON files.

Getting Started

Download the starter code here: meals.html

Instructions

1. Download JSON Functionality

Open this article: https://www.jameslmilner.com/posts/downloading-a-file-with-javascript/

Using it as a reference, implement the download button to:

  • Put all the form data into an object
  • Convert the object to a JSON string
  • Make the browser download it as a .json file

2. Upload JSON Functionality

Open this article: https://javascript.info/file

Using it as a reference, implement the upload button to:

  • Read the selected file from the file picker (this has been started for you)
  • Parse the file’s text back into an object
  • Fill in the form fields with the loaded data

Other Resources

Testing

  1. Fill in the meal form with your selections
  2. Click “Download JSON” to save your data
  3. Refresh the page (or clear the form)
  4. Use the file picker to select your saved JSON file
  5. Click “Upload JSON” to restore your data
  6. Click “Calculate Calories” to verify the graph displays correctly

Submission

Submit your completed meals.html file.