如何使用 Javascript 将 JSON 附加到现有文件? [英] How to append JSON to already existing file with Javascript?

查看:28
本文介绍了如何使用 Javascript 将 JSON 附加到现有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为data.json"的数据文件,其中包含一些 JSON 或者它可以是空白的.我创建了一个函数,将我的 JSON 字符串打包到一个变量中,所以如果我这样做了,

Let's say I have a data file named "data.json" which contains some JSON or it can be blank. I created a function that packs my JSON string inside a variable, so if I do,

var myJSONVar = myJSONString;
console.log(myJSONVar);

我会打印,

[{ "my":"JSON" }]

如何使用 Javascript 将 myJSONVar 的内容转储到data.json"文件,而无需使用服务器端语言或外部 JS 库?这完全不可能吗?

How can I dump the content of myJSONVar to the "data.json" file with Javascript, without the need to use a server side language or external JS library? Is this totally impossible?

推荐答案

我不认为这是不可能的,除非您谈论的是遗留机器,在这种情况下,您将需要某种服务器回显.

i don't think it's very impossible, unless you are talking about legacy machines, in which case you'll need a server echo of some sort.

在所有三个主要浏览器的当前版本中,您可以从带有 JS 的字符串中下载具有自定义名称的文件:

in current versions of all three major browsers you can download a file with a custom name from a string with JS:

<script>
//from: http://danml.com/js/download.js
function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "," + escape(strData);


    if (window.MSBlobBuilder) {
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) {
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    } /* end if('download' in a) */
    ; //end if a[download]?

    //do iframe dataURL download:
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
} /* end download() */


   var myJSONVar = [{ "my":"JSON" }];
   download( JSON.stringify(myJSONVar, null, "\t"), "data.json", "text/plain");
</script>

这篇关于如何使用 Javascript 将 JSON 附加到现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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