Skip to content

Instantly share code, notes, and snippets.

@n8jadams
Last active August 19, 2022 21:11
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 n8jadams/0af69123a5f8286cb746c835d903c196 to your computer and use it in GitHub Desktop.
Save n8jadams/0af69123a5f8286cb746c835d903c196 to your computer and use it in GitHub Desktop.
Download a javascript object as a JSON file
async function downloadObjectAsJSONFile(object: any, filename: string): Promise<void> {
if(!filename.endsWith('.json')) {
filename = `${filename}.json`
}
const json = JSON.stringify(object)
const blob = new Blob([json],{ type:'application/json' })
const href = await URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = href
link.download = filename
link.style.position = 'absolute'
link.style.left = '200vw'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment