node.js - 如何清理 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}`))
解决方案
正则表达式应该可以解决问题。我不确定在您的代码中应该在哪里进行剥离,但这是一个使用正则表达式去除方括号和引号的示例函数:
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
推荐阅读
- redirect - 如何将所有子域重定向到主页
- redis - 将 redis.conf 文件移动到 AMI 时,Packer 给我 SCP 权限被拒绝
- numpy - ValueError:检查输入时出错:预期 conv2d_16_input 有 4 个维度
- python - 使用 TensorFlow 进行多元线性回归
- django - Django 两个依赖下拉列表
- django - 我如何使用 django rest 框架返回可序列化的 json?
- php - 使用 sum,group by 从不同的表访问查询
- html - 从 python 循环结果到 django
- python - python Tkinter - 滚动两个命令
- python - 如何重塑张量并获得Tensorflow中的第一个维度?