0

How do I Create a new json file programmatically using JavaScript?

Given the following snippet, I need to push the info array into a file.

$("#submit").click(function jsonCreator() {
    let nameGetter = document.getElementById("nameINPT").value;
    let ageGetter = document.getElementById("ageINPT").value;

    let info = {
        name: nameGetter,
        age: ageGetter,
    }
})
4
  • Will need to send to server using ajax and manage files there. Commented Oct 1, 2019 at 11:46
  • You can create JSON strings from javascript objects/arrays easily with JSON.stringify(info). If you want to store it as a file you will need send it the your server first. You can't create files on the client pc (luckily) Commented Oct 1, 2019 at 11:47
  • What do you mean, you want to create a file that the user can download? Commented Oct 1, 2019 at 11:48
  • I want to create a file at my own pc. Commented Oct 1, 2019 at 11:55

1 Answer 1

2
JSON.stringify(info)

Will convert your javascript Object to Javascript Object Notation (JSON).

But you can not create a file on the server(or your pc) with javascript running on the client side. As client side javascript does not have access to server file system. But you can create and directly download that file to the client computer like this:

$("#submit").click(function jsonCreator() {
    let nameGetter = document.getElementById("nameINPT").value;
    let ageGetter = document.getElementById("ageINPT").value;

    let info = {
        name: nameGetter,
        age: ageGetter,
    }


    var element = document.createElement('a');
  element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(info)));
  element.setAttribute('download', 'myfile');

  element.style.display e= 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);

})

Note: did not have a chance to test the code. But used the solution described here to save the file

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

2 Comments

So what you your saying is that there is no way to create new json file on my self pc? does the only way is by localstorage and by requests?
@SahiBalata you can't access File System via Browser's JavaScript engine

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.