Reputation: 23
I have a file with multiple json objects, single object can span multiple lines. How do I iterate over all objects in a file using nodejs.
Background: I am monitoring a service using REST api, and writing it stats to a file continuously over a period of time. I want to process that file and plot graph of various parameters.
Example
{
"items" : 534,
"latency" : 23,
"errors": 4
}
{
"items" : 493,
"latency" : 22,
"errors": 3
}
....
Upvotes: 1
Views: 837
Reputation: 2841
If the file actually looks like that, (like several JSON files concatenated in a single file), then you are doing it wrong.
Just change it, so the file becomes an array that contains the different objects, so it looks something like this:
[
{
"items" : 534,
"latency" : 23,
"errors": 4
},
{
"items" : 493,
"latency" : 22,
"errors": 3
}
]
Then you could use regular methods to iterate arrays:
var objects = require('./your_json_file.json');
objects.forEach(function (obj) {
console.log(obj.items);
});
Upvotes: 1