Pass Python array to javascript? - 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?
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.

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

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
}

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

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

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

Related

adding object to array using .splice()

I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}

Json in javascript

i am getting a problem to get json string creating in javascript,
in console log getting pure json string
like
[{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]
but when i am storing the output of the json in variable
it change like
[{\"elementId\":\"selectProduct\",\"elemnetValue\":\"Y\"},{\"elementId\":\"productId\",\"elemnetValue\":\"415
"}]
so it can't parse by
JSON.parse(jsonString);
You can use JSON.stringify to get a "parseable" string..
like
var str = JSON.stringify([{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]);
var json = JSON.parse(str);
i am done with following code :
var jsonString;
$("#submit").click(function() {
var _intrimForm={
};
var json=[];
var len = document.getElementById("myForm").elements.length;
for(var i=0;i<len;i++){
var _id =document.getElementById("myForm").elements[i].id;
var value = document.getElementById("myForm").elements[i].value;
_intrimForm={
'elementId':_id,
'elemnetValue':value
};
json.push(_intrimForm);
}
console.log(json);
jsonString = JSON.stringify(json);
console.log(jsonString);
readJsonFormElement();
});
function readJsonFormElement()
{
var jsonInterim = new Array();
jsonInterim=JSON.parse(jsonString);
for(var i=0;i<jsonInterim.length;i++)
{
var eId=jsonInterim[i].elementId;
var eValue=jsonInterim[i].elemnetValue;
}
}

javascript array push issue

I have the below object:
Configs = {};
Configs['category'] = [];
Configs['category']['prod1'] = [];
Configs['category']['prod1'].hosts ={
'table': {
'count': 'total_remaining',
'specs': [
{
'name': 'Test 1',
'code': 'BrandName.Cat.Code.[X].Price'
}
]
}
};
I am trying to create an array of elements to be requested from the database using the code below:
var data = Configs["category"]["prod1"].hosts.table;
var count = [data.count];
var names = data.specs;
var namesArray = names.map(function(names) {
var str = names['code'];
var requiredPortion = str.split("[X]");
var newStr = requiredPortion[0];
return newStr;
});
requestData = namesArray.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]); //remove duplicates
requestData.push(count);
console.log(count);
console.log(requestData);
The desired output is:
["BrandName.Cat.Code.", "total_remaining"]
But, when executing my code I am getting the following output:
["BrandName.Cat.Code.", Array[1]]
I am attaching a fiddle link for this. I guess the issue is with array push function usage. Please help.
You just have to remove the square bracket outside the count variable initialization. Try:
var count = data.count;
Instead of:
var count = [data.count];
Fiddle updated.
Replace var count = [data.count]; with count = Object.keys(data).length
Maybe this helps.

How could I create a JSON array in a javascript loop

I would like to create a javascript json array. At the and I would Like to have something like this :
var requestData= {"uris":["SampleName1", "SampleName2", "SampleName3"],"limit":100 };
The names are stored in another variable called result.results.bindings I think my for loop should be like this :
for(binding in result.results.bindings){
// binding holds SampleName1,sampleName2.. etc
}
So how could I create the array that I mentioned above?
Do you mean something like this?
var data = [];
for(binding in result.results.bindings)
data.push(binding);
var returnObject = {uris: data, limit: 100};
I do not know the structure of your data in result.results.bindings, but with the for loop you are looping over the keys of the object / array.
If you want to loop over the values and the data-source is an array you can use this:
var data = [];
result.results.bindings.forEach(function(value) {
data.push(value);
});
var returnObject = {uris: data, limit: 100};
var requestData = {};
var uris = [];
for (binding in result.results.bindings){
uris.push(binding);
}
requestData.uris = uris;
Edited as suggestion from #BenM:
var requestData = {};
requestData.uris = result.results.bindings;
I think for-in loop is not a good practice with array, It's good with object
for(var i = 0, uris = []; i < result.results.bindings.length; i++)
uris.push(result.results.bindings[i]);
var returnObject = {"uris": uris, "limit": 100};
console.log(returnObject);
var data = [];
result.results.bindings.forEach(function(value) {
eval('data.' + value + ' = ' + value);
});
// then access your variables like
alert(data.SampleName1);

Javascript table string to array

I have a string that looks like:
<tr><td>Date</td><td>Value</td></tr>
<tr><td>2013-01-01</td><td>231.198</td></tr>
<tr><td>2013-02-01</td><td>232.770</td></tr>
<tr><td>2013-03-01</td><td>232.340</td></tr>
<tr><td>2013-04-01</td><td>231.485</td></tr>
<tr><td>2013-05-01</td><td>231.831</td></tr>
<tr><td>2013-06-01</td><td>232.944</td></tr>
<tr><td>2013-07-01</td><td>233.318</td></tr>
...which is of course essentially a table.
I'd like to dynamically convert this string into an array containing 2 arrays. One of dates, one of values.
[Edited in]
An array of objects with date and values would work too.
The following::
var input = // your string
var output = $(input).slice(1).map(function(i,el) {
var tds = $(el).find("td");
return { "date" : tds.eq(0).text(), "value" : tds.eq(1).text() };
}).get();
...will return an array of objects in this format:
[{"date":"2013-01-01","value":"231.198"}, {"date":"2013-02-01","value":"232.770"}, ... ]
If you'd like each value to be treated as a number you can convert it like so:
return { "date" : tds.eq(0).text(), "value" : +tds.eq(1).text() };
// add the unary plus operator ---------------^
Then the result will be:
[{"date":"2013-01-01","value":231.198}, {"date":"2013-02-01","value":232.77}, ... ]
While you've already accepted an answer, I thought I'd post a plain JavaScript solution (albeit largely because I spent time working on it, before Barmar pointed out that you're willing and able to use jQuery):
function cellContents(htmlStr, what) {
var _table = document.createElement('table');
_table.innerHTML = htmlStr;
var rows = _table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText',
cells,
matches = {};
for (var w = 0, wL = what.length; w < wL; w++) {
matches[what[w]] = [];
for (var r = 1, rL = rows.length; r < rL; r++) {
cells = rows[r].getElementsByTagName('td');
matches[what[w]].push(cells[w][text]);
}
}
return matches;
}
var str = "<tr><td>Date</td><td>Value</td></tr><tr><td>2013-01-01</td><td>231.198</td></tr><tr><td>2013-02-01</td><td>232.770</td></tr><tr><td>2013-03-01</td><td>232.340</td></tr><tr><td>2013-04-01</td><td>231.485</td></tr><tr><td>2013-05-01</td><td>231.831</td></tr><tr><td>2013-06-01</td><td>232.944</td></tr><tr><td>2013-07-01</td><td>233.318</td></tr>";
console.log(cellContents(str, ['dates', 'values']));
JS Fiddle demo.
For a pure JavaScript solution you can try something like this (assuming str holds your string) :
var arrStr = str.replace(/<td>/g, "").replace(/<tr>/g, "").split("</td></tr>");
var arrObj = [];
var arrData
for (var i = 1; i < arrStr.length - 1; i++) {
arrData = arrStr[i].split("</td>");
arrObj.push({ Date: arrData[0], Value: arrData[1] })
}
It's a burte-force string replacement/split, but at the end arrObj will have array of objects.
if its a valid html table structure, wrap it between table tags, and use jquery to parse it.
then use jquery's selectors to find the columns.
e.g something like this ( pseudo code, havent tried it )
table = $(yourTableString);
dates = table.find("tr td:nth-child(1)");
values = table.find("tr td:nth-child(2)");
Using jQuery:
var table = $('<table>'+str+'</table>');
var result = {};
table.find('tr:gt(0)').each(function () {
var date = $(this).find("td:nth-child(1)").text();
var value = $(this).find("td:nth-child(2)").text();
result[date] = value;
}
:gt(0) is to skip over the header line. This will create an associative array object that maps dates to values. Assuming the dates are unique, this is likely to be more useful than two arrays or an array of objects.

Categories

Resources