javascript - 将 JSON 与可能的差异进行比较 - 如何做到这一点?
问题描述
摘要 - 每 10 分钟 CRON 作业
我的应用程序从网站上抓取数据并按以下格式检索 JSON:
[{
price: '$12,500',
title: '2003 Jeep Wrangler X Sport Utility 2D',
location: 'Valrico, Florida',
miles: '90K miles',
imgUrl: 'https://scontent-mia3-2.xx.fbcdn.net/v/t1.0-0/c43.0.260.260a/p261x260/95585818_10158483215408453_5232171551314411520_n.jpg?_nc_cat=103&_nc_sid=843cd7&_nc_oc=AQnRkSY39Su7LJ3YcapqFxNeys_RLB964OEHIjAMP6T3PwHB2dhHyKL9Y8xLapOUpns&_nc_ht=scontent-mia3-2.xx&oh=48828c46faf75c08d28b656459caaf01&oe=5ED8EA6F',
itemURL: '/marketplace/item/525451485002934/'
},
{
price: '$15,500',
title: '2012 Jeep Wrangler Unlimited Sport SUV 4D',
location: 'Clearwater, Florida',
miles: '95K miles',
imgUrl: 'https://scontent-mia3-1.xx.fbcdn.net/v/t1.0-0/c63.0.260.260a/p261x260/92586992_10156757268737397_3495264851003965440_n.jpg?_nc_cat=111&_nc_sid=843cd7&_nc_oc=AQk_rGSLpKWlkQrYAfXAZXCuV2iZ2cdmVi2lwvjhABGFbFycuawGBR4O-ax3VqUIBX4&_nc_ht=scontent-mia3-1.xx&oh=af5d06bf5564aa9d062ed4427ed1873e&oe=5ED72FA5',
itemURL: '/marketplace/item/2901350359949722/'
}
]
此信息保存到文件newjeeps.json
前端使用此数据在网站上显示。
但...
我只希望新项目显示在页面上。这意味着,每次运行脚本时,我都想显示尚未显示的项目。
所以我想我会比较两个结果,并将差异保存到 newjeeps.json ,所以网页总是会显示新项目。正确的?
我只是在比较标题。如果标题匹配,则从最终数组中删除。(是的,在一个完美的世界里......)
那么这是我的代码。它不会出错,但也不会保存不同的项目。我想删除重复项,并重新保存新数据。
const initScraper = async () => {
// Get currently listed items on Marketplace
const items = await getItems('Jeep Wrangler');
console.log(items);
// Get OLD Jeeps
const existingResults = jsonfile.readFileSync(fileName);
const ex = existingResults.length;
var existingTitle;
var newTitle;
var newItems = [];
/* Loop through EXISTING (newjeeps.json) */
for (var i = 0; i < ex.length; i++) {
/* Existing Title */
existingTitle = existingResults[i].itemTitle;
/* Loop through NEW data */
for (y = 0; y < items.length; y++) {
/* New Title */
newTitle = items[y].itemTitle;
/* Do we have a match? */
if (existingTitle == newTitle) {
//console.log("match");
// Remove from new results
items.splice(y, 1);
// Change detected?
changed = true;
}
}
}
if (changed) {
const page2 = await browser.newPage();
await page2.goto(`http://john.mail.com/mail.php`);
jsonfile.writeFile(fileName, items, function (err) {
if (err) console.error(err)
})
}
console.log("done");
}
有谁看到出了什么问题?
谢谢你。
解决方案
此问题的根本原因是您试图访问itemTitle
对象中不存在的属性。
newTitle = items[y].itemTitle;
这应该纠正如下。
newTitle = items[y].title;
推荐阅读
- sql - MS Access - 更新单元格的值
- python - 如何从 django 中的数组中读取输入
- lambda - 使用 terraform 的自定义 API 网关授权器
- c++ - 如何使文本在饼图的每个切片中居中?
- javascript - selectize.js 在动态创建的选择元素上
- windows - 使用 pywin32 库中的 win32evtlog 写入 Windows 事件日志
- tfs-power-tools - TFPT 跨工作区取消搁置/迁移
- powershell - 将表对象导出到 CSV
- android - xml不能有多个根标签android
- ruby-on-rails - 根据属性值从Ruby中的数组中删除/删除对象