user310291 user310291 - 3 months ago 23
Node.js Question

Why JSON.stringify returns undefined

Why does console.log(JSON.stringify(row.data)) returns undefined and how to fix it ?

From https://jsfiddle.net/ys6j038q/3/

var data = '{"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}}';

var sanitized = '[' + data.replace(/}{/g, '},{') + ']';
var rows = JSON.parse(sanitized);
console.log(rows);

for(var row in rows){
console.log(JSON.stringify(row.data));
console.log(JSON.stringify(row.data));
}

Answer

Because rows is an array.

Try this instead of the for loop.

rows.forEach(row => console.log(JSON.stringify(row.data)))

or

rows.forEach(function(row) { console.log(JSON.stringify(row.data)) })

forEach is an iterator that you can call on arrays

The forEach() method executes a provided function once per array element.

Docs on forEach

You could also use a for loop

for(var i = 0; i < rows.length; i++) {
    console.log(JSON.stringify(rows[i].data))
}
Comments