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
            }
        }
    });
}
10
  • What is the error you are getting when using JSON.parse. Add actual sample array. Commented Oct 3, 2015 at 17:37
  • Console shows "Uncaught SyntaxError: Unexpected token". It is provided inside jsfiddle, but I will add it to the OP too. Commented Oct 3, 2015 at 17:38
  • Are the array values wrapped in quotes. If you directly put the array from file does it run? Commented Oct 3, 2015 at 17:41
  • You need to wrap the array values with quotes. jsfiddle.net/5yz95ktg/3 Commented Oct 3, 2015 at 17:42
  • provide demo with full example including csv parsing. Too many unknowns considering that the current demo works fine Commented Oct 3, 2015 at 17:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You were the first to actually post an answer (instead of comments), so picking yours as the correct answer. Thanks everyone!
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.

Comments

-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.

1 Comment

I was able to easily change the regex since I restructured the csv to begin with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.