javascript - 如何将文本文件作为数组读取
问题描述
我有一个如下所示的文本文件(不是 json):
['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']
我如何读取它并放入 2 个数组:['a'、'b'、'c'、'd'] 和 ['e'、'f'、'g'、'h']?
我正在使用它来读取文件:
jQuery.get('filename.txt', function(data){
alert(data);
});
解决方案
解决方案1:
\r\n
用 multiline( )分割字符串- 循环遍历拆分的字符串数组并将单引号替换为双引号以使其成为有效的 JSON 字符串
- 解析 JSON 字符串
JSON.parse
const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;
const multiLineTextToArray = (txt) => {
return (txt.match(/[^\r\n]+/g) || []).map((line) => {
// replace single quote with double quote to make it proper json string
// then parse the string to json
return JSON.parse(line.replace(/\'/g, '\"'));
});
};
/**
jQuery.get('filename.txt', function(data){
alert(multiLineTextToArray(data));
});
*/
// example
console.log(multiLineTextToArray(exampleData));
解决方案 2:构造一个有效的 JSON 数组
\r\n
用 ','替换 multiline( )- 用双引号替换单引号
- 用
[]
- 解析 JSON 字符串
JSON.parse
const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;
const multiLineTextToArray = (txt) => {
return JSON.parse(`[${txt.replace(/[\r\n]+/g, ',').replace(/\'/gm, '\"')}]`);
};
/**
jQuery.get('filename.txt', function(data){
alert(multiLineTextToArray(data));
});
*/
// example
console.log(multiLineTextToArray(exampleData));
推荐阅读
- selenium - 针对 .NET Core Web 应用运行 Selenium 测试
- javascript - 如何在 Angular 应用程序中订阅 setInterval()?
- hbase - Hbase 定期批量加载 HFiles 和次要压缩关系
- python - 登录 GCP 和本地
- rust - 如何在匹配期间访问枚举变量的字段而不显式绑定它?
- kubernetes - 是否可以在 Kubernetes 中运行具有高可用性、检查点和保存点的单容器 Flink 集群?
- c - Web 程序集 - 类型错误:尝试获取资源时出现网络错误
- php - 尝试使用 phpMyAdmin 创建理论数据库时出错
- r - 当您有是/否列时,在 R 中绘制分组条形图
- windows - 英特尔 OpenVINO:验证安装时出错