首页 > 解决方案 > 如何清理 NodeJS 中的数据(删除括号和引号)?

问题描述

我有一个 csv 表,其中一些单元格可以有单个记录或多个记录,如数组。示例单元格看起来像 ["London"] 或 ["Cairo", "Montreal", "Paris"] - 包括括号。我正在使用 sever.js 在网页上的可视化中显示这些记录。

一切都很好,除了括号和引号显示在可视化中。如何在 nodeJS 中编写规则/逻辑,以使括号和引号都不会显示在最终的可视化中?

清理 csv 文件本身中的数据是没有意义的,因为我将不得不将这段代码用于数百个 csv 文件,所以最好在 nodeJS 中编写规则。

以下是我目前使用的 server.js 代码:

/**
* API for getting country Names
*/
app.get('/get-country-names.json', (req, res) => {
william.william().then(response => {
    res.json(response);
}).catch(message => res.send("Failed to read file" + message));
});

/**
* API to read file and return response in json
* Takes country id as parameter
*/
app.post('/get-city-sources.json', (req, res) => {
let countryName = req.body.countryName;
let city = req.body.city;

william.william().then(sources => {
    let filteredSources = [{ name: city, parent: null, color: 'red' }];
    Array.from(new Set(sources.filter(source => source.countryName === countryName && source.city === city).map(src => src.source)))
    .forEach(source => {
        let sourceArr = source.split(',');
        console.log(sourceArr);
        sourceArr.forEach(src => filteredSources.push({ name: src, parent: city, color: 'blue' }));
    });
    res.json(filteredSources);
}).catch(message => res.send("Failed to read file" + message));
});

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

标签: node.jscsv

解决方案


正则表达式应该可以解决问题。我不确定在您的代码中应该在哪里进行剥离,但这是一个使用正则表达式去除方括号和引号的示例函数:

const formatCellString = (cell = '') => {
  return cell
    // strip out the square brackets
    .replace(/^\[(.*?)\]$/, "$1")
    // strip out the quotes
    .replace(/("\b)|(\b")/g, '')
}

formatCellString('["Cairo", "Montreal", "Paris"]'); => // Cairo, Montreal, Paris
formatCellString('["London"]'); => // London

推荐阅读