3

I have a JSON file that contains multiple objects of the same structure that look like this:

{
   "id": "123",
   "type": "alpha"
}
{
   "id": "321",
   "type": "beta"
}

I'm using node.js to read the file.

fs.readFile(__dirname + "/filename.json", 'utf8', function(err, data) {
var content = JSON.parse(JSON.stringify(data));

If I do a console.log(content) things look good. I see the content of the json file. I'm trying to iterate over each object but I'm not sure how to do that. I've tried using

for(var doc in content)

but the doc isn't each object as I was expecting. How do I loop over the content to get each object in a json format so that I can parse it?

RUEMACHINE
  • 381
  • 2
  • 9
  • 23

3 Answers3

1

If content is an array, you can use

content.forEach(function (obj, index) { /* your code */ })

See documentation for Array.prototype.forEach()

Guido
  • 46,642
  • 28
  • 120
  • 174
Daniel Diekmeier
  • 3,401
  • 18
  • 33
0

if you need to just iterate, a forEach loop would work or a normal for loop :

for(var i = 0; i<content.length(); i++){
//perform whatever you need on the following object
var myobject  = content[i];
}
Osama Salama
  • 647
  • 1
  • 8
  • 17
-2

Depend of the files, the two current answer (Osama and Daniel) assume you have a JSON Array:

[
    {
        "id": "123",
        "type": "alpha"
    },
    {
        "id": "456",
        "type": "beta"
    }
]

In which case, you can use any array iterator:

var async = require('async'),
    content = require(__dirname + "/filename.json");
async.each(content, function (item, callback) {
    //...
});

But in your case, it seems to not be JSON (no bracket to indicate array, and no comma to separate the objects), so in the case JSON.parse doesn t throw up any error, you'll need to isolate your objects first:

var fs = require('fs'),
    async = require('async');

fs.readFile(__dirname + "/filename.notjson", 'utf8', function(err, data) {
    var content = data.split('}');
    async.map(content, function (item, callback) {
        callback(null, JSON.parse(item));
    }, function (err, content) {
        console.log(content);
    };
});
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
  • You don't need to use async library to loop through an array – simon-p-r May 15 '16 at 21:58
  • @simon-p-r: sure, but it s late here, and I m not sure of the correct syntax for `array.map`/`forEach`, while with async I m sure the script is functionnal, if not optimal. – DrakaSAN May 15 '16 at 22:00
  • this goes to a direction what I'm looking for whan reading the title of the question. unfortunately, the solution which searches for `}` is too basic for most structures – Daniel Alder Dec 13 '17 at 22:56