Pass Python Array To Javascript?
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?
Solution 1:
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);
});
Solution 2:
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}
Solution 3:
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]}
Solution 4:
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);
Solution 5:
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);
functionparse(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);
}
Post a Comment for "Pass Python Array To Javascript?"