Created
May 9, 2017 20:08
-
-
Save davorbadrov/bf3eb42ba6ce5285cb2ceda3a95c52ce to your computer and use it in GitHub Desktop.
Read JSON file in frontend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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