6
var proj = {
    Name : "abc",
    Roll no : 123
};

How can I write proj data in JSON format in .json file in javascript?

2
  • 1
    JSON.stringify(proj) to convert it from Javascript to JSON. It would be worth going through a JSON basics course to teach yourself how to create JSON from scratch though, this is a very basic question. Commented Jul 17, 2017 at 16:09
  • 2
    You've got 2, identical and working, answers that have solved your problem. Commented Jul 17, 2017 at 16:27

4 Answers 4

19

You can save the json object in file.json file like this.

const FileSystem = require("fs");
 FileSystem.writeFile('file.json', JSON.stringify(proj), (error) => {
    if (error) throw error;
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Should be (err) => { if (err) throw err; }
13

JSON.stringify (introduced in ES 5.1) will convert the object into a string of JSON.

var json = JSON.stringify(proj);

JavaScript has no built-in mechanism for writing to a file. You generally need something non-standard provided by the host environment. For example, Node.js has the writeFile method of the File System module.

Comments

0

Pretty much the same as top answer but slightly simpler version I regularly use to help with debugging (prints out an object at a given point in the code without using a debugger):

require('fs').writeFile('file.json', JSON.stringify(proj), (error) => {
        if (error) {
            throw error;
        }
    });

Comments

0

One way to get a file in a browser with JS is using a dataUri:

var dataUri = "data:application/json;charset=utf-8;base64," + btoa(JSON.stringify(proj));
<a download="proj.json" href=dataUri>proj.json</a>

cheers,

jD

Comments

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.