Skip to content

Instantly share code, notes, and snippets.

@benjaminadk
Created November 6, 2018 04:10
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 benjaminadk/bdd902daabb26a603eedd03ff58319fd to your computer and use it in GitHub Desktop.
Save benjaminadk/bdd902daabb26a603eedd03ff58319fd to your computer and use it in GitHub Desktop.
Exam Simulator - Download JSON
// Example State
this.state = {
name: "Johnny Smitherson",
age: "47",
employed: true
}
// Method to download as JSON file
downloadFile = () => {
const {name, age, employed} = this.state
const obj = {
name,
age: parseInt(age, 10),
employed
}
const filename = "example.json"
const str = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(obj))}`
const node = document.createElement('a')
node.setAttribute('href', str)
node.setAttribute('download', filename)
document.body.appendChild(node)
node.click()
node.remove()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment