Skip to content

Instantly share code, notes, and snippets.

@n8jadams
Created March 1, 2022 19:15
Show Gist options
  • Save n8jadams/99fce29561b65de49449755230e67afc to your computer and use it in GitHub Desktop.
Save n8jadams/99fce29561b65de49449755230e67afc to your computer and use it in GitHub Desktop.
A function to help downloading a javascript object as a JSON file
export async function downloadObjectAsJSONFile(object, filename) {
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.position = 'absolute'
link.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