Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save JSON data on local file

In my program, I get a JSON format data using JSON.stringify(). Now I want to save this JSON object on a file.

My question is: how can I save the JSON data on a file created locally when clicking on a button on jquery?

My JSON object is like this:

{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}
like image 384
N.Malloul Avatar asked Dec 09 '25 13:12

N.Malloul


2 Answers

You could use the Blob constructor and URL.createObjectURL() to create a temporally anchor tag with the download attribute set to what ever name your downloadable file should have and then trigger a click event on that anchor element. This will unfortunately not work in any browser, but the support for Blob constructor is actually pretty good.

Here is an example.

var data = '{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}';


document
.querySelector('#download')
.addEventListener('click', function() {

  var blob = new Blob( [ data ], {
      type: 'application/octet-stream'
  });

  var url = URL.createObjectURL( blob );
  var link = document.createElement( 'a' );
  link.setAttribute( 'href', url );
  link.setAttribute( 'download', 'data.json' );

  link.click()

  URL.revokeObjectURL(url)

})
<button id="download">Download</button>
like image 154
DavidDomain Avatar answered Dec 11 '25 03:12

DavidDomain


twFile check this jquery plugin.

that allows you to read and write to a local file.

i hope this can help you

like image 37
hadi Avatar answered Dec 11 '25 02:12

hadi