2017-04-14 44 views
0

我想每次存儲gameQuestion功能遍歷, 但當輸出變爲JSON字符串只給了我最後的 值,而不是所有的值。我可以看到所有的值,當我 console.log,但我需要存儲所有的值。存儲JSON字符串到一個數組

var express = require('express'); 
var fs = require('fs'); 
var request = require('request'); 
var cheerio = require('cheerio'); 
var app = express(); 

app.get('/scrape', function(req, res) { 


url = 'http://streak.espn.com/en/'; 

request(url, function(error, response, html){ 
    if(!error) { 
     var $ = cheerio.load(html); 

     var gameQuestion, propVal; 
     var json = { gameQuestion : "", propVal : ""}; 

     $('.gamequestion').each(function(){ 

      var data = $(this); 
      gameQuestion = data.text(); 
      console.log(gameQuestion); 
      json.gameQuestion = gameQuestion; 

     }); 

     $('.mg-check.mg-checkEmpty.requireLogin').each(function() { 
      var data = $(this).attr('selectionid'); 

      propVal = data; 
      console.log(propVal); 
      json.propVal = propVal; 
     }); 
    } 


    fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){ 

     console.log('File successfully written! - Check your project directory for the output.json file'); 
    }); 

    res.send('Check your console!'); 

    }); 
}); 



app.listen('8081'); 

console.log('magic happens on port 8081'); 

exports = module.exports = app; 
+0

你需要存儲你的價值觀,但你只是簡單地覆蓋它 –

回答

0

更改類型的var json = { gameQuestion : "", propVal : ""};財產gameQuestion數組var json = { gameQuestion : [], propVal : ""};並在其推過迭代

$('.gamequestion').each(function(){ 
    var data = $(this); 
    gameQuestion = data.text(); 
    console.log(gameQuestion); 
    json.gameQuestion.push(gameQuestion); 
}); 

console.log(json.gameQuestion); 
+0

謝謝!這就是我需要的 – tin

0

申報gameQustion作爲陣列; i.e. var gameQuestion = ["",""];然後每個值推到陣列json.gameQuestion.push(gameQuestion);

相關問題