【发布时间】:2017-01-03 15:03:30
【问题描述】:
对于标题中缺少信息表示歉意,我想不出一个更好的来描述我的问题。
我目前正在构建一个简单的脚本,用于从另一个网站抓取数据,并最终在自定义获取的数据后,
将结果输出为JSON。
代码没有“错误”或“损坏”,我也没有收到任何错误,只需要稍微改进一下我的脚本。
下面是我用 Express 编写的脚本,用于为其他网站获取播放器:
router.get('/teams/:id/roster', function(req, res) {
var id = req.params.id;
var url = 'http://www.testdata.dev/api/teams/' + id;
request(url, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html); // load the DOM with Cheerio
$('#roster').filter(function () {
var player, line, lines = [], forward = {}, defense = {};
line = {
"forwards": forward
};
// Iterate over all the forwards
$("#forwards > tbody > tr > td").each(function(index) {
var that = $(this);
player = that.text().trim(); // F.e "Lebron James", "Michael Jordan"
// Create a new line after every three players (in total of 12 forwards, in total of 4 lines)
if(index % 3 == 0) {
lines.push({
"line": {
"forwards": [player]
}
});
} else {
lines[lines.length - 1]["line"]["forwards"].push(player);
}
});
// Output results as JSON
res.contentType('application/json');
res.json(lines);
});
} else {
console.log("Request was not made");
}
});
});
当前 JSON 输出:
[
{
"line": {
"forwards": [
"Player 1",
"Player 2",
"Player 3"
]
}
},
{
"line": {
"forwards": [
"Player 4",
"Player 5",
"Player 6"
]
}
},
// ...
// In total of 4 lines
]
所以代码完成了它的工作,我能够输出JSON,如上所述。但是,我想根据以下规则集为每个球员分配一个属性:每个“线”对象中输出的第一个球员将始终是 LW(左翼),第二个球员将始终是 C(中锋)和第三名 RW(右翼)。
很遗憾,我无法自己实现此功能,因此我需要您的帮助。提前致谢!
预期的 JSON 输出:
{
"lines": [{
"line": {
"forwards": {
"LW": "Player 1",
"C": "Player 2",
"RW": "Player 3"
}
}
}, {
"line": {
"forwards": {
"LW": "Player 1",
"C": "Player 2",
"RW": "Player 3"
}
}
}]
}
【问题讨论】:
-
forwards是指输出中的对象还是数组? -
^^ 因为当前的“预期 JSON 输出”不是有效的 JSON。另请注意,JSON 的对象属性没有顺序。
-
为什么不
var output = {forwards:{"LW":input.forwards[0], "C":input.forwards[1]...?我看不出这里有什么困难。 -
@DenysSéguret 是的,
forwards是一个对象。我已经编辑了预期的输出,因为它不是有效的 JSON。
标签: javascript jquery json express cheerio