我一直在尝试找到一种可行的解决方案,但找不到。
我在javascript中有一个对象,其中有一些非英语字符。
我正在尝试以下代码将对象转换为Blob以供下载。
当我单击以下载内容时,在打开下载的JSON时,非英语字符变得乱七八糟。
这是一个像这样的简单对象: {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);
}
您的encode
函数已损坏,因为它将字符代码转换为字节。不要尝试自己实现它,只需使用Encoding API即可:
const str = JSON.stringify(obj);
const bytes = new TextEncoder().encode(str);
const blob = new Blob([bytes], {
type: "application/json;charset=utf-8"
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句