0

I am trying to export a json to file using html and js.

This is my code:

<form onsubmit="return make_json(this);">
    name: <input type="text" name="first"/><br>
    <input type="submit" value="JSON"/>
</form>

<pre id="output">
    your json here
</pre>

<script>
    function make_json(form) {
        var json={
            "first": form.first.value
        };

        var str = JSON.stringify(json, 0, 4);
        document.getElementById('output').innerHTML = str;

        return false;
    }
</script>

As you can see, I displayed that json to the main page in html, but I have no idea how to export it to a file. I searched for an answer for a long time, but nothing helped me or mostly I couldn't understand the answer. Can anybody clarify this to me?

Mr. Wizard
  • 1,093
  • 1
  • 12
  • 19
  • In order to save the file to the server, you would have to upload it using an ajax call. To save it to the client inside the browser environment, you would use "localStorage", but to save it outside of the browser environment, so it is accessible like any other file in the file system, you need to have the user interact and save it, as with the C. Mürtz answer below. – Grax32 Sep 03 '17 at 12:02

1 Answers1

2

I think you want to download a file with the json as content right?

FileSaver.js makes this easy: https://github.com/eligrey/FileSaver.js/

var json = "YOU JSON";
var blob = new Blob([json], {type:"application/json;charset=utf-8"});
FileSaver.saveAs(blob, "export.sjon");
C. Mürtz
  • 454
  • 1
  • 3
  • 10