I've been trying to find a solution that works but couldn't find one.
I have an object in javascript and it has some non-english characters in it.
I'm trying the following code to convert the object to a blob for download.
When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.
It's a simple object like this one: {name: "שלומית", last: "רעננה"}
function setJSONForDownload(obj) {
obj = obj || []; // obj is the array of objects with non-english characters
const length = obj.length;
if (length) {
const str = JSON.stringify(obj);
const data = encode( str );
const blob = new Blob( [ data ], {
type: "application/json;charset=utf-8"
});
const url = URL.createObjectURL( blob );
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute( 'href', url );
downloadElem.setAttribute( 'download', 'data.json' );
}
else {
document.getElementById('download').innerText = `No data to download...`;
}
}
function encode (s) {
const out = [];
for ( let i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
}
Uint16Array()
. Char codes are 16 bits, not 8. Then make the type"application/json;charset=utf-16"
as well. – Cavit