Mohammad Ali
Mohammad Ali

Reputation: 352

Convert string in array form to actual array

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]]]'

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
            }
        }
    });
}

Upvotes: 4

Views: 7635

Answers (3)

&#193;ngela
&#193;ngela

Reputation: 1425

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.

Upvotes: -1

Adam Mazzarella
Adam Mazzarella

Reputation: 763

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.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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.

Upvotes: 1

Related Questions