如何将javascript对象转换为utf-8 Blob进行下载? [英] How to Convert a javascript object to utf-8 Blob for download?

查看:885
本文介绍了如何将javascript对象转换为utf-8 Blob进行下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找到一种可行的解决方案,但是找不到.

I've been trying to find a solution that works but couldn't find one.

我在javascript中有一个对象,其中有一些非英语字符.
我正在尝试以下代码将对象转换为Blob以供下载.
当我单击以下载内容时,打开下载的JSON时,非英语字符变得乱七八糟.

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.

这是一个像这样的简单对象:{name: "שלומית", last: "רעננה"}

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);
}

推荐答案

您的encode函数已损坏,因为它将字符代码转换为字节.不要尝试自己实现,只需使用编码API :

Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:

const str = JSON.stringify(obj);
const bytes = new TextEncoder().encode(str);
const blob = new Blob([bytes], {
    type: "application/json;charset=utf-8"
});

这篇关于如何将javascript对象转换为utf-8 Blob进行下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆