passing python list to javascript - javascript

I am trying to pass a python list to a javascript function, but it doesn't work... I think the Javascript function will see it as one long string. This is what I do:
#webiopi.macro
def calcSunriseSunsetOneYear():
o=ephem.Observer()
o.lat='51.21828'
o.long='3.94958'
s=ephem.Sun()
d=datetime.date.today()
t=timedelta(days=1)
d=d+t
o.date=d
riseTime=[]
setTime=[]
s.compute()
for x in range (0,365):
o.date=o.date+1
riseTime.append(str(ephem.localtime(o.next_rising(s))))
setTime.append(str(ephem.localtime(o.next_setting(s))))
return(json.dumps(riseTime))
This is the python data:
["2015-03-22 06:43:02.000006", "2015-03-23 06:40:46", "2015-03-24 06:38:31.000001", "2015-03-25 06:36:15.000002", "2015-03-26 06:33:59.000003", "2015-03-27 06:31:44.000004", "2015-03-28 06:29:28.000005", "2015-03-29 07:27:13.000006", "2015-03-30 07:24:57", "2015-03-31 07:22:42.000001", "2015-04-01 07:20:27.000002", "2015-04-02 07:18:13.000003", "2015-04-03 07:15:58.000004", "2015-04-04 07:13:44.000005", "2015-04-05 07:11:31.000006", "2015-04-06 07:09:17", "2015-04-07 07:07:04.000001", "2015-04-08 07:04:52.000002", "2015-04-09 07:02:40.000003", "2015-04-10 07:00:28.000004"]
In Javascript I do this:
var printChart = function macroCallBack(macro, args, chartInfo) {
document.getElementById("chartInfo").innerHTML=chartInfo;
var arLength=chartInfo.length;
console.log("arLength is: ",arLength);
for (var i=0; i<arLength; i++) {
console.log(chartInfo[i]);
}
}
And the console prints every character of the python list on a seperate line, like this:
[
"
2
0
1
5
etc...
I can't format the above console.log output, but every character is on a seperate line.
Also the length of the array is exactly the same as the length of the total string, so my conclusion is the python list is transformed to Javascript as one long string...
I hope someone can help me out!

You are right, you are looping through a string. This is because json are strings. This makes it pretty easy to pass data between different programming languages as strings are data types implemented in almost every programming language. However since it are strings you need to decode the string to a usable format/object. In javascript you can use the methodJSON.parse().
jsfiddle demo
var frompythonjsonstring ='["2015-03-22 06:43:02.000006", "2015-03-23 06:40:46", "2015-03-24 06:38:31.000001", "2015-03-25 06:36:15.000002", "2015-03-26 06:33:59.000003", "2015-03-27 06:31:44.000004", "2015-03-28 06:29:28.000005", "2015-03-29 07:27:13.000006", "2015-03-30 07:24:57", "2015-03-31 07:22:42.000001", "2015-04-01 07:20:27.000002", "2015-04-02 07:18:13.000003", "2015-04-03 07:15:58.000004", "2015-04-04 07:13:44.000005", "2015-04-05 07:11:31.000006", "2015-04-06 07:09:17", "2015-04-07 07:07:04.000001", "2015-04-08 07:04:52.000002", "2015-04-09 07:02:40.000003", "2015-04-10 07:00:28.000004"]';
macroCallBack(frompythonjsonstring);
function macroCallBack (str) {
obj = JSON.parse(str)
for (var i=0; i<obj.length; i++) {
console.log(obj[i]);
}
}

You should look at JSON.stringify and JSON.parse javascript methods that will turn string into Javascript objects. Hope this helps

Related

SyntaxError: Unexpected number when pulling JSON data

I am trying to pull the IncPubKey JSON data from "0", but I'm getting a SyntaxError. In postman, part of the returned data looks like this:
"ShardCommittee": {
"0": [{
"IncPubKey": "12RRMGAEXdtD796sbmyHwNv9oiPPfGYa1r6KssMqXyiUMfT6r86",
"MiningPubKey": {
"bls": "184UyUYNPg1ESgEXzUZY6dWjxohyZSvE4f5XnkssHhonRNopAp2bxqxCAToYGUsgeyrWeKQJmnLkgeCm95XYK5mjD2KjFPKkrrwLyiXscUAJ9mVubTCft4Z1ra3S9Ca4ojx1P5ajMNaS2Yc9C1rh8qr2S7VE6KCk7YMnBpdkyWdiTrmGtUUjx",
"dsa": "16Be2DoUxNMzxidLKBqDC6gMkqMZ9bSijBvpRirvioZiqmVGDkg"
}
},
{
"IncPubKey": "1VVQRGZFhMyp9LRS1yjyXsW6ugMqtHaYyUYMLutRhy6ASF7AWf",
"MiningPubKey": {
"bls": "1ELnsFdz5M4RDvShVvcAKE4bbv6dZED31MeSKgRKhDiYgTiJeWT94zvw2VHeytVxEDExMeemPqXL7DA1CnNBGbjTMarv1vXd1A6oi5JctfM4u8Totjpqr8VNFtQbgHqJ1wSYdFz5hgwEq8QkmDdf71WPPdYEkpG5ow3DYeAAwFkArQZvn1C4F",
"dsa": "18BTfn7mbDBXgysaHZsrGqbN3T2K3gEChsEXXuzkwKEo96eU3Nf"
}
},
But in google, it doesn't seem to like the number "0."
for (let i = 0; i < d.Result.ShardCommittee.0.length; i++) {
sh1.getRange(i + 2, 3).setValue(d.Result.ShardCommittee.0[i].IncPubKey);
}
When I step back and pull all data into one cell:
sh1.getRange(2, 3).setValue(d.Result.ShardCommittee);
This is the returned result:
{ 0=[Ljava.lang.Object;#41d079f7, 1=[Ljava.lang.Object;#7197d9a6, 2=[Ljava.lang.Object;#23a1916a, 3=[Ljava.lang.Object;#657f1624, 4=[Ljava.lang.Object;#c3808bd, 5=[Ljava.lang.Object;#186f5f86, 6=[Ljava.lang.Object;#60f6425c, 7=[Ljava.lang.Object;#6cc43c2c}
Any idea how to re-write that to pull the IncPubKey data?
You can't use a number as a key in "dot" notation, instead use array style notation:
Result.ShardCommittee["0"].length;
and
d.Result.ShardCommittee.["0"][i].IncPubKey
This is a javascript syntax issue, rather than a Google Apps Script specific issue.
in your last example, where you write the entire object to a cell, you are seeing the results of converting the structure to a string. If you want to write raw objects to a cell in the spreadsheet for inspection, you should convert them to JSON first.
sh1.getRange(2, 3).setValue(JSON.stringify(d.Result.ShardCommittee));

javascript json get data names out for object

Still newbie #this, hope not a silly question.
I get from a java backend a json.
For this question I assigned a with that json string.
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
let b=a.data;
let s="";
for (i in b) {s += b[i]};
$('#msg').html(s);
As output I get object Object (small capital, big capital)
In the end I need to run over "data' and print or store that keynames : blablaMOUTI blablaDAN , blablaDAA blablaALHAZO ... on screen or in a simple array list.
The values after the keynames or a empty string, that's fine, I need only the keynames.
Found some semi simular questions, but I don't get it to work. The answers I found all trust I know already the keynames.
You can do it like this:
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
var keys = [];
for(i = 0; i< a.data.length; i++){
for(var k in a.data[i]) {
keys.push(k);
}
}
console.log(keys)
For testing purpose this will populate an array with keys that you wanted, but you can manipulate the result as you wish
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
Try this:
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

node red array / how to "use" specific place

in node red i collect values with "Collector" the collector sends me an "Object" with all pairs of values when one of them is updated:
{ "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
with "json" and after with "stringsplit" i got an array of f.e. 9 values:
array [9] (can be up to 80 pairs of values)!
[ "{", "mqtt/1/", ":", "-127.00", ",", "mqtt/0/", ":", "41.61", "}" ]
now i want to have a function node which compares the Value (-127.00) from the Topic (mqtt/1/) with the Value (41.61) from the Topic (mqtt/0/).
this i working ...BUT only if i know which is the first topic/value and which is the second...
var outputMsgs = msg.payload;
var top1=outputMsgs[1];
var val1=outputMsgs[3];
var top2=outputMsgs[5];
var val2=outputMsgs[7];
msg = {payload: val1}
var msg2 = {payload: val2}
if (val1>val2)
{var msgOUT={payload: "BIGGER"};}
return [msg, msg2, msgOUT];
But the Problem is, that sometimes "mqtt/1/" comes first, sometimes "mqtt/0/" and values will be switched. So now, maybe somebody can help to write a function to pick the right value with the right topic to compare them in the next step.
Maybe is there a Way to look if the topic contains 0, 1 ...80, and then save it in this order in a array???
Thank you in advance!
If the initial msg.payload is truly a javascript object as you describe, ie:
msg.payload = { "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
then you can reference the two values as:
var value1 = msg.payload["mqtt/1/"];
var value1 = msg.payload["mqtt/2/"];
If msg.payload is actual a JSON string, then pass the message through a JSON node first to convert it to the object.
There is no need to try splitting the string yourself and parsing the content.

Java: Get JavaScript Array Elements from page

I am at a point where I can pull a single javascript declaration such as:
var cars = ["Saab", "Volvo", "BMW"];
parsed from a page.
I would like to be able to get all the elements of the array ("Saab", "Volvo", "BMW") from this declaration.
Should I be using some javascript engine for this, or what else would be the best way to get javascript variable values from my Java code.
I would hate to reinvent the wheel if something is already out there that is able to do this, so I am just looking for advice on something I can use to do this function.
I assume you found a way to transport that javascript object/array into your Java domain as a String or Stream. What you want now is a JSON parser.
One way is to use json.org or other libraries. Further information about json parsing can be found in this thread:
How to parse JSON in Java
The [org.json][1] library is easy to use. Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
} You may find extra examples from: [Parse JSON in Java][2]
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
[1]: http://www.json.org/java/index.html
[2]: http://theoryapp.com/parse-json-in-java/
You might also want to look into jsonb (https://jcp.org/en/jsr/detail?id=353) that was introduced with Java 7. You can bind an object model and transform JSON objects into java objects and vice versa.
you can iterate through all the values in 'window'
for ( var key in window )
{
if ( typeof window]key] == 'object' && window]key].length > 0 )
{
//this is the array you are looking for
}
}
You can get access to javascript object from java by using httpunit
Method 1: JSON parser, as Alex's answer.
Method 2: Javascript parser for Java
Method 3: Regular Expression (A weird way I figured out!)
First pattern is var\s+([a-zA-Z0-9]+)\s+=\s+\[(.*)\]\s*;*
var + one or more space(s) + variable name($1) + one or more space(s) + equals sign + one or more space(s) + array content($2) + ......
Second pattern is "(.*?)", get the string between two quotation marks.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSParser {
public String arrayName;
private String tempValues;
public ArrayList<String> values = new ArrayList<String>();
public boolean parseJSArray(String arrayStr){
String p1 = "var\\s+([a-zA-Z0-9]+)\\s+=\\s+\\[(.*)\\]\\s*;*";
Pattern pattern1 = Pattern.compile(p1);
Matcher matcher = pattern1.matcher(arrayStr);
if(matcher.find()){
arrayName = matcher.group(1);
tempValues = matcher.group(2);
Pattern getVal = Pattern.compile("\"(.*?)\"");
Matcher valMatcher = getVal.matcher(tempValues);
while (valMatcher.find()) { // find next match
String value = valMatcher.group(1);
values.add(value);
}
return true;
}else{
return false;
}
}
}
With JDK 8 the code bellow works :
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String js = "var carsfromjs = [\"Saab\", \"Volvo\", \"BMW\"]";
engine.eval(js);
String[] cars = (String[])engine.eval("Java.to(carsfromjs, \"java.lang.String[]\")");
for(int i=0; i<cars.length; i++){
System.out.println(cars[i]);
}
You can find many ways to access Javascript code throught "nashorn" :
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/

javascript multiline dict declaration

I'm having an issue. I want to have a static dict
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
There are a lot of entries, and I want to have an easy access to all of them in case I need to change their value. Because of this, I don't like the single-line declaration.
As an alternative, I did manage to do the following, since multi-line text is allowed in Javascript:
var dict = {};
var loadDict = function() {
text = "aaa,true\n\
aab,false\n\
aac,false\n\
aad,true\n\[...]";
var words = text.split( "\n" );
for ( var i = 0; i < words.length; i++ ) {
var pair = words[i].split(",");
dict[ pair[0].trim() ] = pair[1].trim();
}
}
Is there a better/more elegant way of having a multi-line declaration of a dict?
note: Creating multiline strings in JavaScript is a solution only for strings. it doesn't work with a dict.
edit: I was adding a '\' at the end of each line. That was the issue. thanks.
var myDict = {
"aaa": true,
"aab": false,
"aac": false,
"aad": true,
[...]
};
I hope this is what you meant, because it's basic Javascript syntax.
Also, if for some reasons you want to "store" simple objects (made of strings, numbers, booleans, arrays or objects of the above entities) into strings, you can consider JSON:
var myDictJSON = '{\
"aaa": true,\
"aab": false,\
"aac": false,\
"aad": true,\
[...]
}';
var myDict = JSON.parse(myDictJSON);
Support for JSON is native for all the major browsers, including IE since version 8. For the others, there's this common library json2.js that does the trick.
You can also convert your simple objects into string using JSON.stringify.
that's easy-
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true
};
please remember, don't place the curly bracket in the next line.
i like responses. Please respond
This (a complex data structure containing both "string" and "booleans"):
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
Can be expressed like this:
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true,
[...]
};
Similarly, this:
var myBigHairyString = "Supercalifragilsticexpialidocious";
Can be expressed like this:
var myBigHairyString =
"Super" +
"califragilstic" +
"expialidocious";

Categories