【问题标题】:Create json file using blob使用 blob 创建 json 文件
【发布时间】:2014-11-27 07:16:35
【问题描述】:

我已经在字符串中编写了 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); 

现在将 json 转换为 blob?

【问题讨论】:

  • 定义“blob”。您选择的标签在这种情况下没有意义。

标签: javascript jquery json blob


【解决方案1】:

试试这样的

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】:

    试试下面的代码:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 2012-07-29
      • 2018-01-10
      • 1970-01-01
      • 2015-07-26
      • 2015-09-11
      • 1970-01-01
      • 2012-10-03
      相关资源
      最近更新 更多