28

I have a back-end JavaScript file that runs on node.js. It do some stuff using async.series and yields the final dictionary(object) with data I need on my front-end. I now how to read a .json file and convert it into the JavaScript object, but I do not know create .json file with back-end JavaScript and how to store some data in it.

Could anyone please tell me the right way to do this.

Here is the dictionary(object) that I need to convert and store to the .json file.

var dict = {"one" : [15, 4.5],
            "two" : [34, 3.3],
            "three" : [67, 5.0],
            "four" : [32, 4.1]};
0

2 Answers 2

35

Simple! You can convert it to a JSON (as a string).

var dictstring = JSON.stringify(dict);

To save a file in NodeJS:

var fs = require('fs');
fs.writeFile("thing.json", dictstring);

Also, objects in javascript use colons, not equals:

var dict = {"one" : [15, 4.5],
        "two" : [34, 3.3],
        "three" : [67, 5.0],
        "four" : [32, 4.1]};
Sign up to request clarification or add additional context in comments.

4 Comments

ok, but how can I create .json file and store this string into it?
Check the answer now, should be ok
tnx but fs.writeFile(...) requires a third (or fourth) parameter which is a callback function to be invoked when the operation completes.
@ashkannasirzadeh this is right. I just edited this answer so it can work fine.
18

1- make your obj:

var dict = {"one" : [15, 4.5],
    "two" : [34, 3.3],
    "three" : [67, 5.0],
    "four" : [32, 4.1]};

2- make it JSON:

var dictstring = JSON.stringify(dict);

3- save your json file and dont forget that fs.writeFile(...) requires a third (or fourth) parameter which is a callback function to be invoked when the operation completes.

var fs = require('fs');
fs.writeFile("thing.json", dictstring, function(err, result) {
    if(err) console.log('error', err);
});

2 Comments

But then how do you generate a json file output
Thanks for adding this answer, I was getting invalid callback error. probably an old version of fs worked without the callback

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.