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}
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>
twFile check this jquery plugin.
that allows you to read and write to a local file.
i hope this can help you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With