将json字符串存储到数组中

时间:2017-04-14 20:32:06

标签: javascript jquery json

  

我试图在每次函数循环时存储gameQuestion,   但是当输出转到json字符串时,它只给我最后一个   值而不是所有值。我可以看到所有的价值观   console.log,但我需要存储所有值。

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;

2 个答案:

答案 0 :(得分:0)

将gameQustion声明为数组; i.e. var gameQuestion = ["",""];然后将每个值推送到数组json.gameQuestion.push(gameQuestion);

答案 1 :(得分:0)

gameQuestion中的属性类型var json = { gameQuestion : "", propVal : ""};更改为数组var json = { gameQuestion : [], propVal : ""};并将其推入迭代次数

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

console.log(json.gameQuestion);