Writing a json object to a text file in javascript

后端 未结 2 1140
抹茶落季
抹茶落季 2020-11-30 04:54

I have a JSON object in javascript. I want to simply write the JSON object to a text file. From the things that I came across so far indicate that it is not possible to do s

相关标签:
2条回答
  • 2020-11-30 05:25

    Perhaps this solution is a little more elegant, tested in Chrome, FF and ie7 to ie10, tested with text, JSON, PDF and XLS data (using the appropriate content type)

    Either supply the saveFile() function with a data blob, or create a data blob on the fly with type set to nothing and your data between the []'s

    In this example, we'll just stringify the settings object, and set the datatype correctly.

    settings = { any_kind_of_object: true };
    json_str = JSON.stringify(settings);
    
    saveFile('yourfilename.json', "data:application/json", new Blob([json_str],{type:""}));
    
    function saveFile (name, type, data) {
        if (data != null && navigator.msSaveBlob)
            return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    
        var a = $("<a style='display: none;'/>");
        var url = window.URL.createObjectURL(new Blob([data], {type: type}));
        a.attr("href", url);
        a.attr("download", name);
        $("body").append(a);
        a[0].click();
        setTimeout(function(){  // fixes firefox html removal bug
            window.URL.revokeObjectURL(url);
            a.remove();
        }, 500);  
    }
    
    0 讨论(0)
  • 2020-11-30 05:34

    One thing you can do is setup the JSON as a download on the fly.

    var data = "{name: 'Bob', occupation: 'Plumber'}";
    var url = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
    window.open(url, '_blank');
    window.focus();
    

    Working demo: http://jsfiddle.net/sLq3F/

    Apart from that, you can't write a JSON to a file on the clientside due to security reasons. (Otherwise you have access to the filesystems of your website's users.) You would have to use a server-side language for this, and store the file on the server-side.


    Correction: Looks like you can write to a file, i.e., a "sandboxed section" of the user's filesystem. See Kevin Jantzer's comment below.

    Another Correction: Sorry, the Filesystem API isn't in use. From the HTMl5Rocks website: "In April 2014, it was announced on public-webapps that the Filesystem API spec should be considered dead. Other browsers have showed little interest in implementing it."

    0 讨论(0)
提交回复
热议问题