Alex Kumbhani Alex Kumbhani - 1 month ago 10
Node.js Question

how should i read array data like json?

i have one question i read one txt file and it return array result but i don't know how to read that data like json for json i read like essay but in array i can't .
i got result like

[
{
"id": 0,
"date_created": "2016-08-09 07:31:04",
"date_disabled": "2016-08-19 08:45:03",
"lng": 26.364,
"lat": 58.2456
},
{
"id": 1,
"date_created": "2016-01-02 06:09:15",
"date_disabled": null,
"lng": 26.9283,
"lat": 58.438
},
{
"id": 2,
"date_created": "2016-02-13 01:12:52",
"date_disabled": "2016-03-19 03:35:10",
"lng": 26.3816,
"lat": 58.074
},
{ ....


and my code is

fs.readFile('data.txt', function(err, data) {
if(err)
{
throw err;
}

var array = data.toString().split("\n");
for(i in array)
{
console.log(array[i]);
}
});


now what i exactly want is . i want to read date_created and date_disabled from that output , i try something like this

for(i in array)
{
console.log(array[i].date_created);
}


but i got undefined result so how should i got
date_created
please help me for this.

qxz qxz
Answer

To get a JSON string (e.g., from reading a file) into an actual JavaScript object, use JSON.parse(string). Here is an example:

fs.readFile('data.txt', function(err, data) {
    if (err) throw err;

    var array = JSON.parse(data); // converts the JSON string into an actual object/array
    // use array as you did in your question...
});

BONUS: Use a for...of loop to process each element of the array:

for (var obj of array) {
    console.log(obj.date_created);
    // etc.
}

Note that this is only available since ECMAScript 6, but since you're using Node.js, that shouldn't be a problem.