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 + ']');
});
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);
});
All you need is to change quote and do following -
var strArr = '[["Parrot", "Green"], ["Crow", "Black"], ["Duck", "White"]]';
var finalArr = JSON.parse(strArr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.