CodingNic

Import and Export

Validate Imported Data

Import and Export 9 min read

Validate Imported Data

Imported files are external input, so do not replace the current task list immediately after parsing JSON.

First check that the parsed value is an array and that each task contains the fields your application expects.

A simple validation pass can look like this:

javascript
const isValidTask = (task) => {
  return (
    task &&
    typeof task === "object" &&
    typeof task.id === "string" &&
    typeof task.title === "string" &&
    typeof task.completed === "boolean"
  );
};

if (!Array.isArray(importedTasks) || !importedTasks.every(isValidTask)) {
  return;
}

Keep any additional fields your task model uses, such as due dates and priority, when validating and applying imported tasks.

Checkpoint

Try importing your valid exported file, then try an invalid JSON file or JSON containing the wrong structure. Invalid data should not replace the current tasks.