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?

1
  • 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. Commented Sep 3, 2017 at 12:02

1 Answer 1

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");

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

4 Comments

Not download exactly, just write into a file the result. I don't know if this is possible, I am new to this
I tried something like this: var txtFile = "./file.json"; var file = new File(txtFile,"write"); file.open(); file.writeline(str); file.close();
No this is not possible! You need to download it! If you could change files on disk it would be a security risk...
Oh, I see. Then I download it. Ty very much!

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.