1

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
}
....

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chris, This approach did worked, I had to change my data collection to script to save data in array format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.