Javascript 使用 blob 创建 json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26158468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:26:08  来源:igfitidea点击:

Create json file using blob

javascriptjqueryjsonblob

提问by josaric

I have written json code in string and i want to send it using xmlhttp as .json file. Is it possible to do it with blob?

我已经用字符串编写了 json 代码,我想使用 xmlhttp 作为 .json 文件发送它。可以用blob来做吗?

var cleanScript = {
    'type': 'script',
    'api_key': api_key,
    'data': data,
    'inputs': inputs,
    'timeoutSeconds': timeoutSeconds
};
var jsonse = JSON.stringify(cleanScript, null, 2); 

Now json to blob?

现在json到blob?

回答by Gildas.Tambo

Try something like this

尝试这样的事情

var cleanScript = {
    'type': 'script',
    'api_key': api_key,
    'data': data,
    'inputs': inputs,
    'timeoutSeconds': timeoutSeconds
};
var jsonse = JSON.stringify(cleanScript);
var blob = new Blob([jsonse], {type: "application/json"});
var url  = URL.createObjectURL(blob);

var a = document.createElement('a');
a.href        = url;
a.download    = "backup.json";
a.textContent = "Download backup.json";

document.getElementById('json').appendChild(a);
<div id="json"></div>

回答by yarmyarch

Try the code below:

试试下面的代码:

    var int2ByteArray = function(i, minByteCount) {
        var result = [],
            buf = code = +i,
            offsetCount = 0;
        while ((buf = code>>(8 * offsetCount)) || offsetCount < minByteCount) {
            buf = buf & 0xFF;
            ++offsetCount;
            result.push(buf);
        }
        return result.reverse();
    };

    var ascii2ByteArray = function(s) {

        if (!s) return 0;
        var result = [];
        [].map.call(s, function(c) {
            result = result.concat(int2ByteArray((typeof(c)).toLowerCase() == "number" ? c : c.charCodeAt(0)));
        });
        return result;
    };

    // You got the blob here, do whatever you want.
    var blob = new Blob(new Uint8Array(ascii2ByteArray(jsonse)), {type:"text/json"});

The matrix is to convert a string(stringfied by JSON.stringify) in to a Uint8Array that could be used making a blob. I happened make something like that before, hope it's useful.

矩阵是将字符串(字符串化JSON.stringify)转换为可用于制作 blob 的 Uint8Array。我之前碰巧做过这样的事情,希望它有用。