Reputation: 1582
If I store an array using a txt file, how can I load it back to jQuery?
Assuming the external txt is
['Parrot', 'Green'], ['Crow', 'Black'], ['Duck', 'White']
How can I load it as
var myArr = [ ['Parrot', 'Green'], ['Crow', 'Black'], ['Duck', 'White'] ];
This is what I've been trying. Does not work.
var myArr;
$.ajax({url: 'files/external.txt'}).done(function(d) {
myArr = JSON.parse('[' + d + ']');
});
Upvotes: 0
Views: 1424
Reputation: 2759
All you need is to change quote and do following -
var strArr = '[["Parrot", "Green"], ["Crow", "Black"], ["Duck", "White"]]';
var finalArr = JSON.parse(strArr);
Upvotes: 0
Reputation: 29322
Your trying to parse 'external' as JSON, but the content does not adhere to the JSON-specification.
Try wrapping all text inside double-quotes instead of single-quotes.
//external.json
[
[
"Parrot",
"Green"
],
[
"Crow",
"Black"
],
[
"Duck",
"White"
]
]
Your code could then look like
$.ajax({url: 'files/external.json'}).done(function(d) {
myArr = JSON.parse(d);
});
Upvotes: 2