javascript - 为什么我的 JSON 文件显示单个键中的所有值?

标签 javascript json node.js

我废弃了一个使用 Node.js 环境的网站。我已解析 JSON 格式的数据并将 JSON 数据保存在名为 output.js 的文件中

但不是为不同的值创建不同的键(使用不同的数组),而是将整个数据(值)存储在单个键中。我使用了“each”函数并形成了一个循环将它们存储在不同的数组中,但这似乎不起作用。

可能出现什么故障?

这是代码:

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

var allJSONdata = [];

 request ('http://www.bseindia.com/corporates/ann.aspx',
  function (error, response, html) {
     if(!error && response.statusCode == 200){

     var $ = cheerio.load(html);
     var allRecords = $('div.content');

     allRecords.each(function(index, element){ 
     var title = $(element).find('td.TTHeadergrey').text();

     var tempData = {
         Header:title
        }
     allJSONdata.push(tempData);
     });

   }
  fs.writeFile('output.json', JSON.stringify(allJSONdata), function(err){  
    console.log('successfully saved');
})
});

我的output.json数据如下:

[{"Header":" /*all heads in this single key*/ "}]

最佳答案

您没有使用正确的选择器,所以...更改此:

     var allRecords = $('div.content');

     allRecords.each(function(index, element){ 
     var title = $(element).find('td.TTHeadergrey').text();

     var tempData = {
         Header:title
        }
     allJSONdata.push(tempData);
     });

对此:

var allRecords = $('.content .TTHeadergrey');


allRecords.each(function(index, element){
    if( (index % 5)===0 ||  (index % 5)===1){
        var title = $(element).text();
        var tempData = {
            Header:title
        };
        allJSONdata.push(tempData);
    }
});

关于javascript - 为什么我的 JSON 文件显示单个键中的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705627/

相关文章:

javascript - Node promise 循环等待结果

JavaScript - 如何从 JSON 对象中获取特定值

javascript - Joomla 1.5/CK 表格 : Need help debugging font size on javascript tooltip

javascript - 将 JSON 数据链接到 d3 中的 g 元素

html - Angular : Failed to load images: 404 (Not Found)

json - 简单的结构化数据(INI、YAML、JSON 等)编辑器应用程序

mysql - 从 js 运行时插入错误,xampp shell 使用相同的 sql 工作正常

javascript - window.location.href 返回一个文件夹?

json - 从后台线程修改自动布局引擎

node.js - 仅为一条路线 express 设置特定的 bodyParser