Как я могу прочитать текстовый файл в виде массива - PullRequest
0 голосов
/ 26 января 2020

У меня есть текстовый файл (не 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);
});

Ответы [ 2 ]

1 голос
/ 26 января 2020

Решение 1:

  1. разделить строку на несколько строк (\r\n)
  2. l oop через разделенный массив строк и заменить одиночный -т кавычка с двойной кавычкой, чтобы сделать ее действительной JSON строкой
  3. парсингом 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 массива

  1. заменить многострочное (\r\n) на ', '
  2. заменить одинарные кавычки на двойные
  3. обернуть всю строку []
  4. , проанализировать строку 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));
0 голосов
/ 26 января 2020

мой подход к этому будет следующим:

данные содержат всю информацию из файла .txt. Поэтому я бы попытался прочитать файл построчно, используя функцию разбиения следующим образом.

var arrays = []; 

jQuery.get('filename.txt', function(data){

var splitted = data.split("\n"); // --> should return an array for each line 

// Loop through all lines 
for(var i = 0; i < splitted.length; i++) 
{

var line = splitted[i]; 

// Now you could remove [ and ] from string  
var removed = line.replace('[','').replace(']','');

// Now you can split all values by using , delimiter
var values = removed.split(',');  
 var array = []; // this will be a single array

// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++) 
{

var value = values[c]; 

// Now you can add this value to your array
// this depends on the data structure you are using in JS 
// for example
array.push(value);  

}

// NOw all values are stored in first array so add it to the multi array
// this is an array in an array
arrays.push(array); 

}

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...