1

Im trying to loop through a json file and pick out every episode, but I'm confused that my loop only output the first current_episode, much appreciated if anyone can check my problem!

app.get('/episodes', function(req, res){
    fs.readFile('channels.json', 'utf8', function (err, data) {
        var jsondata = JSON.parse(data);
        for (var i=0; i<jsondata.channels.length; i++){
            var myChannel = jsondata.channels[i].current_episode;
            res.send(myChannel);
        }
    })
}); 

My json data:

{
  "total": 70,
  "request_uri": "\/channels\/",
  "channels": [
    {
      "channel_id": 42,
      "current_episode": [
        {
          "id": 126248,
          "title": "Spanarna",
        }
      ]
    },
    {
      "channel_id": 43,
      "current_episode": [
        {
          "id": 126255,
          "title": "Beck: I stormens \u00f6ga",
        }
      ]
    },
............
}

5 Answers 5

7

res.send writes the data and ends the request. Try this instead:

app.get('/episodes', function(req, res){
    fs.readFile('channels.json', 'utf8', function (err, data) {
        var jsondata = JSON.parse(data);
        res.writeHead(200, {'Content-Type': 'text/plain'});
        for (var i=0; i<jsondata.channels.length; i++){
            var myChannel = jsondata.channels[i].current_episode;
            res.write(JSON.stringify(myChannel));
        }
        res.end();
    })
}); 
Sign up to request clarification or add additional context in comments.

4 Comments

got error TypeError: first argument must be a string or Buffer
@nihulus If myChannel isn't a string you need to convert it to one. Simplest would be JSON.stringify(myChannel)
@nihulus If title is a property of current_episode, that's how you'd do it.
@nihulus Then current_episode in this case must be null. Log it to the console to help debug it.
2

Try building a string of your episodes.

app.get('/episodes', function(req, res){
    fs.readFile('channels.json', 'utf8', function (err, data) {
        var jsondata = JSON.parse(data),
            myChannel = [];
        for (var i=0; i<jsondata.channels.length; i++){
            myChannel.push( jsondata.channels[i].current_episode );
        }
        res.send( myChannel.join("\n") );
    })
});

2 Comments

i got a output all data is object [object object]
Oops, yea you'd need to do have another loop to loop over the current_episode since it's also an array based on your structure.
1

Because you have res.send(myChannel) inside the loop. res.send is sending the first channel as it finds and ignores the next calls to res.send().

Instead of this you should concatenate all the channels into a string and issue a res.send(allChannels) outside the loop.

Comments

0

Easiest way I found was:

You could try the following, however it will also load all the keys into memory

Object.keys(o).forEach(function(key, index, originalObject) {
  var val = o[key];
  logic();
});

However since Object.keys is a native method it may allow for better optimisation.

Whilst this was the code I would have always done I found this here (slightly more transparent code) whilst checking if this was the most optimal way to do things: Iterate over object keys in node.js

Comments

-1
function search_items( args ) { 
if ( args ) {       
    string = args.toLowerCase().replace(/"/g, "").replace(/'/g, "").split(" ");
    for ( var i=0, j=0; i<string.length; i++ ) {        
    (function(i){           

        vocabulary.findOne({word:string[i]}, function(error, search){ // find vocabulary info

        if ( !error && search ) {
j++;
        pages.findOne({voc_id:ObjectID(search._id)}, function(error, pages){ // find pages info

            if ( !error && pages ) {

            page_tokens.findOne({page_id:ObjectID(pages._id), voc_id:ObjectID(search._id)}, function(error, page_token){ // find page tokens info

                if ( !error && page_token ) {

                pos_tags.findOne({_id:ObjectID(page_token.pos_tag_id)}, function(error, pos_tag){ // find pos_tags info

                    if ( !error && pos_tag ) {

                    resultTotal.push({vocabulary:search.word, pages:{doc:pages.base_url+pages.path}, page_tokens:{sentence_number:page_token.sentance_number,token_position: page_token.token_position}, pos_tags: { tag:pos_tag.tag } });
                    j--;
                    console.log(j);
                    if ( j==0 ) {

                        res.json({success:resultTotal});

                    }

                    } else {
                    res.json({ error:true });                       
                    }           

                });

                } 

            });             
            }           
        });         
        }           
    });     
    })(i)       
    }
} 
}

Comments

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.