Jason
Jason

Reputation: 95

Error when attempting to create a blob from a JSON.stringified object

I have an object that is stringified successfully, but then there's an error when a blob is attempted to be created from it: "Uncaught TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence." A file with the proper name is then successfully downloaded, but it has no contents. Might someone know what I'm doing wrong when creating the Blob? Thanks!

This is the code I'm using for exporting the file:

const data = JSON.stringify(arrayObject);
const blob1 = new Blob(data, { type: "text/plain;charset=utf-8" });
const name = this.currentUser.username + ".json";

//Check the Browser.
const isIE = false || !!document.documentMode;
if (isIE) { window.navigator.msSaveBlob(blob1, name); }
else {
    const url = window.URL || window.webkitURL;
    const link = url.createObjectURL(blob1);
    var a = $("<a />");
    a.attr("download", name);
    a.attr("href", link);
    $("body").append(a);
    a[0].click();
    $("body").remove(a);
}

Upvotes: 2

Views: 1662

Answers (1)

Jason
Jason

Reputation: 95

https://javascript.info/blob describes the constructor syntax as new Blob(blobParts, options), where blobParts is an array of Blob/BufferSource/String values. The issue is fixed when the first line is changed to the following:

const data = [JSON.stringify(arrayObject)];

Upvotes: 3

Related Questions