我正在编写一个 api,在发出 get 请求后我将发送回一些数据。我正在从 CSV 文件中读取数据,然后只发回特定列名的数据。我可用的列是
[
'YEAR',
'TICKETS SOLD',
'TOTAL BOX OFFICE',
'TOTAL INFLATION ADJUSTED BOX OFFICE',
'AVERAGE TICKET PRICE',
''
]
以下是我正在使用的 Kaggle 数据集的一些示例数据。
YEAR,TICKETS SOLD,TOTAL BOX OFFICE,TOTAL INFLATION ADJUSTED BOX OFFICE,AVERAGE TICKET PRICE,
2021,"42,37,74,881","$3,881,777,912","$3,881,777,912",$9.16,
2020,"22,36,38,958","$2,048,534,616","$2,048,534,616",$9.16,
2019,"1,22,85,41,629","$11,253,443,955","$11,253,444,050",$9.16,
我可以很好地读取数据,甚至可以在客户端正确显示数据。当我尝试访问该YEAR
字段时出现问题。对于该特定字段,我得到undefined
所有行。其他领域不会发生这种情况。当我尝试访问其他字段时,它们会正确返回每一行的值。我不确定为什么会这样。
这是我的 app.js(主文件)
const express = require('express');
const app = express();
// Middleware
// Routes
app.use('/', require('./routes/test'));
app.use('/movies', require('./routes/annualTicketSales'));
// Start the server
const port = process.env.PORT || 3000;
app.listen(port);
console.log(`Server Listening at ${port}`);
这是我的路线文件
const express = require('express');
const route = express.Router();
const csv = require('csv-parser');
const fs = require('fs');
let data = [];
fs.createReadStream('archive/AnnualTicketSales.csv')
.pipe(csv())
.on('headers', (headers) => {
console.log(headers)
})
.on('data', async(d) => {
console.log(d['YEAR']); // Returns Undefined for all the values
console.log(d['AVERAGE TICKET PRICE']); // Returns the correct value
data.push(d);
})
.on('end', async() => {
console.log("Successfully Read Data");
});
route.get('/ticketSalesAnnual', async(req, res) => {
return res.send(data);
})
module.exports = route;
如您所见,我使用 fs 和 csv-parser 来读取数据。当我尝试这样做时console.log(d['YEAR']);
,我会为每一行返回 undefined 。但是当我使用另一个标题值时,它会返回该列的正确值。我不确定为什么会这样,但是有人可以帮助我解决这种奇怪的行为吗?
以下是我得到的console.log(headers)
[
'YEAR',
'TICKETS SOLD',
'TOTAL BOX OFFICE',
'TOTAL INFLATION ADJUSTED BOX OFFICE',
'AVERAGE TICKET PRICE',
''
]
我刚做时控制台中的输出console.log(d)
如下
{
'YEAR': '2021',
'TICKETS SOLD': '42,37,74,881',
'TOTAL BOX OFFICE': '$3,881,777,912',
'TOTAL INFLATION ADJUSTED BOX OFFICE': '$3,881,777,912',
'AVERAGE TICKET PRICE': '$9.16',
'': ''
}
{
'YEAR': '2020',
'TICKETS SOLD': '22,36,38,958',
'TOTAL BOX OFFICE': '$2,048,534,616',
'TOTAL INFLATION ADJUSTED BOX OFFICE': '$2,048,534,616',
'AVERAGE TICKET PRICE': '$9.16',
'': ''
}
{
'YEAR': '2019',
'TICKETS SOLD': '1,22,85,41,629',
'TOTAL BOX OFFICE': '$11,253,443,955',
'TOTAL INFLATION ADJUSTED BOX OFFICE': '$11,253,444,050',
'AVERAGE TICKET PRICE': '$9.16',
'': ''
}
以下是我使用时的输出console.log(d['YEAR])
undefined
undefined
undefined
以下是我得到的console.log(d['AVERAGE TICKET PRICE']);
$9.16
$9.16
$9.16