6

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>

1 Answer 1

16

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/

Sign up to request clarification or add additional context in comments.

6 Comments

for some reason this seems to remove spaces in json string when the data file is opened
This object {"key":"some text"} ends up like this {"key":"sometext"} in this example .. "some text" is not supposed to merge into "sometext"
@GRowing See updated post. Wrapped $(this).data().obj in encodeURIComponent() jsfiddle jsfiddle.net/kda2rdLy
ahh,, yes,, you're right. thanks for borrowing your eyes to me :)
Had encodeURIComponenet() in js at OP ; neglected to included that portion, here , at original post above
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.