Reputation: 45
I have a text file (not json) that looks like the following:
['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']
How can I read it and put into 2 arrays: ['a', 'b', 'c', 'd'] and ['e', 'f', 'g', 'h']?
I'm using this to read the file:
jQuery.get('filename.txt', function(data){
alert(data);
});
Upvotes: 0
Views: 467
Reputation: 2294
Solution 1:
\r\n
)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));
Solution 2: constructing a valid JSON array
\r\n
) with ','[]
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));
Upvotes: 1
Reputation:
my approach to this would be the following:
data contains all the information from the .txt file. So I would try to read the file line by line using split function like this.
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);
}
});
Upvotes: 0