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?

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

saveAs appears to require a third party library, fyi.
You are right, I thought it is native. Did the first one work? Generating and navigating to the url?
It sure did. The first one however, does not allow for file naming.
@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): stackoverflow.com/questions/25547475/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.