3

I'm new to HTML/javascript. I'm running a local server, with an html/javascript file and a separate python script.

Question: How do I pass a python array to javascript variable?

Work so far: I've written the array to file data.txt:

1  32.1
2  10.0

but I could put it in JSON format if it's easier.

Here's my progress so far:

var x_pos = [];
jQuery.get('http://127.0.0.1:8000/data/data.txt',function(data){

// ??? Code here ???

});

console.log(x_pos[0])

Note: if there is a much simpler way to do this, I'm open to suggestion. Thanks.

1
  • 1
    you could split at every newline, and then again at the space between the number and the value. Commented Aug 28, 2015 at 14:55

5 Answers 5

4
var x_array = [];    
var y_array = [];     

jQuery.get('http://localhost/test/data.txt',function(data){
    var lines = data.split(/\r\n|\n/g);
    for (var i = 0; i < lines.length; i++) {
        line = lines[i].split(/\s+/g);
        x_array.push(line[0]);
        y_array.push(line[1]);
    }
    console.log(x_array);
    console.log(y_array);
});
Sign up to request clarification or add additional context in comments.

6 Comments

What if OP has \r\n as carriage returns?
Updated to handle \r\n case and one or more spaces between the two values in every line of text file.
Yes, this is also what I would do to parse the file split('\n') and line split('\s+')
@MazzCris Thanks , this works pretty well...except that console.log(x_array) returns undefined when outside of the jQuery.get(...) call. Any suggestions? I thought I had a handle on scope :/
@anon0909 jQuery.get() is asynchronous (being a shorthand Ajax function as explained here: api.jquery.com/jquery.get ). Anyway I think you should get an empty array in that case (as it was initialized), not undefined
|
3

Use JSON instead. Then you can just parse it as

jQuery.get('http://localhost/data.txt', function(data) {
  var xy = JSON.parse(data);
});

and use as

alert(xy['1']); // or xy.propertyname if it is not-numeric

Your data structure would be like

{
  "1": 32.1,
  "2": 0
}

7 Comments

It's a text file, how can you use json.parse on something that isn't in json format?
@Daniel_L THIS is a better solution.
The OP specifies that if there's a better way to handle the parsing by changing the format and/or extension of the text file, we should suggest it, So I agree that putting the text in json format would simplify the parsing tremendously and give the OP the simplest way to get the data into variables.
@brso05 I didn't see that initially. I have adjusted my votes accordingly. Without spamming the comments in bold
@anon0909 JSON is very comfortable to use, it is easy to read, it is supported by nearly every programming language which makes it one of the best ways to communicate between client and server.
|
2

Just create a json structure for this and do a JSON.parse(data) after.

Here is your structure:

{x: [1,2,3,4], y:[32.1,10.0,76.3]}

Comments

1

One of the solutions is use split. It splits the string.

    var newData = [];
    data = data.split('\n');
    data.forEach(function(entry){
      entry = entry.split(' ');
      newData.push({
        x : entry[0],
        y : entry[1]
      });
    });
    console.log(newData);

Comments

1

You need to use regular expressions to parse the text file. You cannot just use JSON.parse() on a string that isn't in json format.

http://plnkr.co/edit/39aBGgwvNI7Lem6eiefu?p=preview

$.get("http://localhost/data.txt", parse);

function parse(str) {
    var lineBreak = /\r\n/g;
    var space = /\s/g;
    var tmp = str.split(lineBreak).map(function(l) {
        var split = l.split(space);
        return { key: split[0], val: split[1]  };
    });
    var data = JSON.stringify(tmp, null, 2);
    $("#data").text(data);
}

Comments

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.