Skip to content

Export JSON with Javascript

Andrei Ignat edited this page Jan 14, 2016 · 7 revisions

Video tutorial at YouTube Export JSON with Javascript

#Code I have made code with Jquery, but you can do with the Ajax framework of your choice

    <!-- be sure to include jquery -->
        <a href="#" onclick="return ExportJSON();">Export JSON</a></p>
    </div>
    <script>
        function ExportJSON(){
    //this is your array with data
         var arr=[];
         arr.push({ 'Name':'Andrei Ignat','WebSite':'http://msprogrammer.serviciipeweb.ro/','CV':'http://serviciipeweb.ro/iafblog/content/binary/cv.doc'});
         arr.push({ 'Name':'Your name','WebSite':'http://yoursite','CV':'cv.doc' });
    //we will stringify
          var data = JSON.stringify(arr);
          var id=5;//5=xlsx, 4=docx, 3 = pdf
            var urlData='http://exporter.azurewebsites.net/api/export/ExportFromJSON/' + id;
    //and export            
            Export(urlData, id, data);
            return false;
         
        }
    //extension of the file
        function findExtension(id) {
            switch (id) {
                case 5:
                    return "xlsx";
                case 4:
                    return "docx";
                case 3:
                    return "pdf";
                default:
                    return "notKnown" + id;
            }
        }
    //step 1: POST data, obtain unique id for the export document
    //step 2: obtain file from the unique id
        function Export(urlExport,id, data) {
            var ext = findExtension(id);

    //step 1 - post data
            $.ajax({
                type: "POST",
                url: urlExport,
                data: JSON.stringify({ 'data': data }),
                datatype: "JSON",
                contentType: "application/json; charset=utf-8"
            })
                .done(function(result) {
    //step 2 - obtain file
                    var urlDownload = 'http://exporter.azurewebsites.net/api/export/GetFile/' + result;
                    urlDownload += "?fileName=andrei&extension="+ext;
                    window.location=urlDownload;
                })
                .fail(function(f) {
                    alert("error:" + f.responseText);
                });
        }
        
    </script>

Video at https://youtu.be/sQ762hzxWoo

Clone this wiki locally