我一直在试图找到一种可行的解决方案,但是找不到。
我在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);
}
答案 0 :(得分:3)
您的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"
});
答案 1 :(得分:1)
我找到了一个不错的代码块来解决我的问题。
感谢'pascaldekloe'(https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330)。
只需将编码方法更改为以下内容:
function encode(s) {
var i = 0, bytes = new Uint8Array(s.length * 4);
for (var ci = 0; ci != s.length; ci++) {
var c = s.charCodeAt(ci);
if (c < 128) {
bytes[i++] = c;
continue;
}
if (c < 2048) {
bytes[i++] = c >> 6 | 192;
} else {
if (c > 0xd7ff && c < 0xdc00) {
if (++ci >= s.length)
throw new Error('UTF-8 encode: incomplete surrogate pair');
var c2 = s.charCodeAt(ci);
if (c2 < 0xdc00 || c2 > 0xdfff)
throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
bytes[i++] = c >> 18 | 240;
bytes[i++] = c >> 12 & 63 | 128;
} else bytes[i++] = c >> 12 | 224;
bytes[i++] = c >> 6 & 63 | 128;
}
bytes[i++] = c & 63 | 128;
}
return bytes.subarray(0, i);
}
答案 2 :(得分:1)
调用new Blob([DOMString])
会自动将您的 DOMString (UTF-16)转换为UTF-8。
因此,您只需要new Blob( [JSON.stringify(obj)] )
。
请注意,type
不会在这里使用(只有在进行抓取或您实际尝试读取Blob时才会使用),并且无论如何只会影响文件的获取方式读取(即通过 FileReader.readAsText())读取,但不读取文件的实际内容,因此无需进行设置。
setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);
function setJSONForDownload(obj) {
obj = obj || [];
const length = obj.length;
if (length) {
// DOMString
const str = JSON.stringify(obj);
// text/plain;UTF-8
const blob = new Blob([str]);
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...`;
}
}
<a id="download">dl</a>