2014-10-02 95 views
2

我已经在字符串中编写了json代码,并且我想使用xmlhttp作为.json文件发送它。是否有可能用blob做到这一点?使用blob创建json文件

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

现在json到blob?

+0

定义“blob”。您选择的标签在这种情况下没有意义。 – Quentin 2014-10-02 10:09:27

回答

11

尝试这样的事情

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> 
1

尝试下面的代码:

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 stringfied)在转换成可使用的Uint8Array做一个blob。 我曾经做过类似的事情,希望它有用。