我想每次存儲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;
你需要存儲你的價值觀,但你只是簡單地覆蓋它 –