Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download json object as json file using jQuery

I am looking for ways to download a stringfied json object as file..

I do have one solution as presented in this fiddle example:

FIDDLE

My working version looks like this

HTML

    From data attribute of span:
    <span id="a-data"></span>
    <span id="obj-data" data-obj2='{"obj-1": "text-1","obj-2": "text-2","obj-3": "text-3"}'></span>

JavaScript

    var obj = $("#obj-data").data("obj2");
    var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
    $('<a href="data:' + data + '" download="data.json">Download Me</a>').appendTo("#a-data");

I'd prefer if I could use this HTML. could you suggest a way to approach that?

From data attribute of self:
<div id="data" data-obj='{"obj-1": "text-1","obj-2": "text-2","obj-3": "text-3"}'>
    Download Me
</div>
like image 354
GRowing Avatar asked Oct 22 '15 00:10

GRowing


People also ask

How do I download a JSON file?

Pre-filled JSON can be downloaded after logging into the e-filing portal through: 'My Account -> 'Download Pre-Filled for AY 2022-23' and is imported to the utility for pre-filling the personal and the other opened information. Next Attach the pre-filled file of JSON via the system and Tap on “proceed”.

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.


1 Answers

Try substituting "application/json" for "text/json" , calling .click() on DOM element a , removing a at click handler

$("#data").click(function() {
  $("<a />", {
    "download": "data.json",
    "href" : "data:application/json," + encodeURIComponent(JSON.stringify($(this).data().obj))
  }).appendTo("body")
  .click(function() {
     $(this).remove()
  })[0].click()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="data" data-obj='{"obj-1": "some text","obj-2": "text-2","obj-3": "text-3"}'>
    Download Me
</div>

jsfiddle http://jsfiddle.net/kda2rdLy/

like image 118
guest271314 Avatar answered Oct 03 '22 13:10

guest271314