0

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 + ']');
});
Fergoso
  • 1,584
  • 3
  • 21
  • 44
  • The content of your file doesn't conform to JSON format: there should be double-quotes instead of single-quotes. So you cannot use `JSON.parse`. – hindmost Mar 17 '15 at 10:57
  • JavaScript doesn't have associative array and it sucks ... so use json( ___Valid JSON___ ) like other users are saying – NullPoiиteя Mar 17 '15 at 11:00
  • Did you want this => `var txt = "['Parrot', 'Green'], ['Crow', 'Black'], ['Duck', 'White']", myArr = []; myArr.push(txt);alert (myArr);` – lshettyl Mar 17 '15 at 11:11
  • If you are willing to, and able to, change the entire format of the `.txt`, why not just save the content as a `.js` holding a real array you can include? :) – davidkonrad Mar 18 '15 at 12:31
  • @davidkonrad: good suggestion. thanks. I've got it all sorted and works fine now :) – Fergoso Mar 18 '15 at 12:55

2 Answers2

2

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);
});
Silfverstrom
  • 28,292
  • 6
  • 45
  • 57
0

All you need is to change quote and do following -

var strArr = '[["Parrot", "Green"], ["Crow", "Black"], ["Duck", "White"]]';

var finalArr = JSON.parse(strArr);
Bikas
  • 2,709
  • 14
  • 32