Creating a .json file and storing data in it using JavaScript?

I have a back-end JavaScript file that runs on node.js It does some things using async.series , and gives the final dictionary (object) with the data I need on my interface. Now I read the .json file and converted it to a JavaScript object, but I do not know how to create a .json file with JavaScript back-end and how to store some data in it.

Can someone tell me the correct way to do this.

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

 var dict = {"one" : [15, 4.5], "two" : [34, 3.3], "three" : [67, 5.0], "four" : [32, 4.1]}; 
+7
source share
2 answers

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

 var dictstring = JSON.stringify(dict); 

To save the file in NodeJS:

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

In addition, objects in javascript use colons, not equal:

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

1- make your object:

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

2- do it JSON:

 var dictstring = JSON.stringify(dict); 

3- save your json file and do not forget that fs.writeFile(...) requires a third (or fourth) parameter, which is a callback function that is called after the operation is completed.

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

Source: https://habr.com/ru/post/1201494/


All Articles