Skip to content

Instantly share code, notes, and snippets.

@davorbadrov
Created May 9, 2017 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davorbadrov/bf3eb42ba6ce5285cb2ceda3a95c52ce to your computer and use it in GitHub Desktop.
Save davorbadrov/bf3eb42ba6ce5285cb2ceda3a95c52ce to your computer and use it in GitHub Desktop.
Read JSON file in frontend
// jsonFile can be files[0] from the change event on the input
// it returns a Promise which resolves as JSON content
// or rejects and outputs why it failed
export function readJSON(jsonFile) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = event => {
try {
const jsonContent = JSON.parse(reader.result);
resolve(jsonContent);
} catch (err) {
reject('JSON file seems malformed.');
}
};
reader.onerror = error => {
reject("File couldn't be read");
};
reader.readAsText(jsonFile);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment