0

How can trigger a local to local download of an object as a json file using the Blob API?

const obj = {

  prop1: 'val1',
  prop2: 'val2',
  prop3: 'val3',
  prop4: 'val4',

}

const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});

...triggers a local to local download as myObject.json

Declaring this does nothing?

suchislife
  • 4,251
  • 10
  • 47
  • 78
  • Does this help? https://stackoverflow.com/questions/25547475/save-to-local-file-from-blob The last answer looks like what you're trying to do – Eamonn McEvoy Jul 13 '20 at 14:54
  • Are you asking how to download the obj as a JSON file? If so check out this q/a: [JavaScript blob filename without link](https://stackoverflow.com/q/19327749) – Nick Parsons Jul 13 '20 at 14:54

1 Answers1

1

Do this to get the url. Then navigate to it to download the file.

let blobUrl = URL.createObjectURL(new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}))

Or if you want to download it straight away (edit: by using a library):

saveAs(new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}), "myBlob"); // "myBlob" is the name of the file
feedy
  • 1,071
  • 5
  • 17
  • `saveAs` appears to require a third party library, fyi. – suchislife Jul 13 '20 at 15:05
  • You are right, I thought it is native. Did the first one work? Generating and navigating to the url? – feedy Jul 13 '20 at 15:09
  • It sure did. The first one however, does not allow for file naming. – suchislife Jul 13 '20 at 15:11
  • @suchislife Yeah, use FileSaver to save yourself some time, or if you don't want it, check the last comment in this thread as to how to name the file and download it (by using blob again): https://stackoverflow.com/questions/25547475/save-to-local-file-from-blob – feedy Jul 13 '20 at 15:13