Create json file using blob

ε祈祈猫儿з 提交于 2019-12-09 16:12:14

问题


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?

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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/26158468/create-json-file-using-blob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!