4

I have a text file in this format:

[[Line1TextA,[Lat,Long]], [Line1TextB,[Lat,Long]], ...]
[[Line2TextC,[Lat,Long]], [Line2TextD,[Lat,Long]], ...]
.
.
.

I am parsing a text file (done) and I want to convert strings in array format into actual array and store them as a variable to use.

I tried to use JSON.parse, as suggested here: Convert string containing arrays to actual arrays but I couldn't get it to work (syntax errors). Here is my attempt: https://jsfiddle.net/5yz95ktg/

var myStr = '[[Line1TextA,[Lat,Long]], [Line1TextB,[Lat,Long]]]'

  • var myArr = JSON.parse(myStr);
  • var myArr = JSON.parse("[" + myStr + "]");

Edit:

function readFile(query) {
    $.get('file.txt', function(data) {
        var lines = data.split("\n");    
        for (var i = 0, len = lines.length; i < len; i++) {
            if (lines[i].indexOf(query) > -1) { // Found a match
                var myArr = JSON.parse(lines[i]); // #NOT WORKING
            }
        }
    });
}
Community
  • 1
  • 1
Mohammad Ali
  • 353
  • 1
  • 6
  • 18
  • What is the error you are getting when using `JSON.parse`. Add actual sample array. – Tushar Oct 03 '15 at 17:37
  • Console shows "Uncaught SyntaxError: Unexpected token". It is provided inside jsfiddle, but I will add it to the OP too. – Mohammad Ali Oct 03 '15 at 17:38
  • Are the array values wrapped in quotes. If you directly put the array from file does it run? – Tushar Oct 03 '15 at 17:41
  • You need to wrap the array values with quotes. https://jsfiddle.net/5yz95ktg/3/ – NewToJS Oct 03 '15 at 17:42
  • provide demo with full example including csv parsing. Too many unknowns considering that the current demo works fine – charlietfl Oct 03 '15 at 17:45
  • @Tushar The sample data is how it is inside the file (without quotes). is there any other way than to add quotes to every element? I have like 10k elements total in 150 lines. – Mohammad Ali Oct 03 '15 at 17:48
  • what exactly are you trying to do? Can split each line by csv delimiter into array. Suggest using a parsing library like Papa Parse – charlietfl Oct 03 '15 at 17:49
  • @charlietfl I have already restructured my csv: http://stackoverflow.com/questions/32917717 – Mohammad Ali Oct 03 '15 at 17:51
  • Save yourself the headaches ... http://papaparse.com/ – charlietfl Oct 03 '15 at 17:52
  • I tried PapaParse with this example, but I couldn't get it to work. www.joyofdata.de/blog/parsing-local-csv-file-with-javascript-papa-parse/ – Mohammad Ali Oct 03 '15 at 17:54

3 Answers3

1

Well, you need to make sure they are strings:

var myStr = '[[Line1TextA,[Lat,Long]], [Line1TextB,[Lat,Long]]]'
//-------------^

So change it to:

var str = '[["Line1TextA",["Lat","Long"]],["Line1TextB",["Lat","Long"]]]'

Also make sure you use " inside the JSON, as ' is invalid.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 1
    You were the first to actually post an answer (instead of comments), so picking yours as the correct answer. Thanks everyone! – Mohammad Ali Oct 03 '15 at 21:30
0

For simplicity's sake, Javascript has two types of arrays: numeric and associative. This is similar to other languages but implemented a bit differently. In reality, arrays are really objects where numeric arrays are in an array object and associative are a plain object.

Here are the two syntaxes:

var numericArr = ['foo', 'bar', 'foobar', 42, false];
// numericArr[0] === 'foo'
// numericArr[3] === 42

var assocArr = {'type': 'foo', 'example': 'bar'};
// This can also be written as {type: 'foo'} (keys don't need quotes)
// assocArr['example'] === 'bar'

These arrays can be nested as well, like so:

var mixedArr = {data: ['foo', 'bar'], success: false};

So in your case, the named arrays will need to have curly brackets surrounding them eg.

var myStr = '[{"Line1TextA":["Lat","Long"]}, {"Line1TextB":["Lat","Long"]}]'

Notice also the quotes surrounding the array keys. You'll need that if you would like to JSON parse the data.

If you are not in a position to rewrite the data that is stored in your files, as long as it's in a consistent format you can use something like regex to do your string manipulation to correctly format the data.

Adam Mazzarella
  • 763
  • 1
  • 7
  • 14
-1

You could try to use regex to place the quotes, then use JSON.parse() to parse the properly-formatted json into an array.

var myStr = '[[Line1TextA,[Lat,Long]], [Line1TextB,[Lat,Long]]]';

var json = myStr.replace(/([^\[\],\s]+)/g, '"$&"');
var array = JSON.parse(json);

Working examle: https://jsfiddle.net/397owg7q/

You might need to change the regex a bit, this only works if your data doesn't have whitespace or quotes.

Ángela
  • 1,405
  • 18
  • 24