2017-04-14 4 views
0

Ich versuche, die gameQuestion jedes Mal zu speichern, die Funktion einer Schleife durch, aber, wenn der Ausgang auf das JSON-String geht es gibt nur mir den letzten Wert anstelle allen Werte. Ich kann alle Werte sehen, wenn ich 0 console.log , aber ich muss alle Werte speichern.Speicher json Strings in ein Array

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

Ihre Notwendigkeit, Ihre Werte zu speichern, aber Sie es nur –

Antwort

0

ändern Art der Immobilie gameQuestion in var json = { gameQuestion : "", propVal : ""}; zu Array var json = { gameQuestion : [], propVal : ""}; und drücken sie über Iteration

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

console.log(json.gameQuestion); 
+0

Dank überschreiben! Das habe ich gebraucht – tin

0

Deklarieren gameQustion als Array; i.e. var gameQuestion = ["",""]; dann jeden Wert in das Array schieben json.gameQuestion.push(gameQuestion);

Verwandte Themen