Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating .json file and storing data in it with JavaScript?

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]};
like image 601
Michael Avatar asked Aug 31 '14 09:08

Michael


People also ask

Can you create JSON file in JavaScript?

* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

How JS store data from JSON file?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.

Can JSON be used to store data?

JSON is perfect for storing temporary data. For example, temporary data can be user-generated data, such as a submitted form on a website. JSON can also be used as a data format for any programming language to provide a high level of interoperability.


2 Answers

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]};
like image 78
DevilishDB Avatar answered Oct 04 '22 11:10

DevilishDB


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);
});
like image 32
kia nasirzadeh Avatar answered Oct 04 '22 09:10

kia nasirzadeh