Parsing Javascript Data Object in Java - javascript

Hello i need help in parsing an object that is being return to java. I am running some automated tests using selenium. In my test i am using the framework to call javascript functions and what i am doing is assigning what is passed back from the javascript function to a java object. The event object passed from javascript looks like this
{
data={
isFailover=false,
baseClip={
expression=full,
isAd=true,
connectionBitrate=0,
baseURL=null,
contentCustomData={
fw: titleId=null,
fw: advertiserId=null,
fw: category=null
},
overlays=[],
ratings=[]
}
}
}
I have an object called "responseToMediaIsAd" defined as
private static Object responseToMediaIsAd;
The data response is being outputted (above) comes when i do this
System.out.println(responseToMediaIsAd);
So its great that i get data back:-) The only problem now is HOW do i parse thru this data. do i have to convert it to json then parse that data?... Can someone tell me how to read the value of (say isFailover, and isAd), ie need to know how to step through and get values
I need to know how to use Java to get to this data that Javascript is returning. Thank you

Well, you can use the Jackson JSON parser library, or if you know regex, you can painfully roll a custom one with some crafted queries.

Related

How can I parse these hashes turned string, from my Ruby on Rails API so that it's accessible as an object in Javascript?

The data is stored as an array of objects wrapped in a string that looks like this
["{\"x\"=>15, \"y\"=>7}", "{\"x\"=>14, \"y\"=>7}", "{\"x\"=>13, \"y\"=>7}", "{\"x\"=>13, \"y\"=>6}", "{\"x\"=>13, \"y\"=>5}", "{\"x\"=>13, \"y\"=>4}", "{\"x\"=>13, \"y\"=>3}", "{\"x\"=>12, \"y\"=>3}", "{\"x\"=>11, \"y\"=>3}"]
The reason it is stored that way is because when I was storing the data from a json, I had to convert what was wrapped in Action Parameters to a hash.
I took a look at How to convert a ruby hash object to JSON? and Parse JSON in JavaScript?, and my answer is not addressed.
First, the problem is that it would seem JSON does not parse anything wrapped in double quotations, nor with rocket hash notation, and so I am not able to convert to convert "{"x"=>15, "y"=>7}" to {"x"=>15, "y"=>7}.
Perhaps, I have to serialize the object, see where I get my data from here: How can I access the data for the snake object sent through JSON in my params?
Any ideas on what the right approach would be?
Following radiantshaw's lead, using either
eval("{\"x\"=>15, \"y\"=>7}")
or
JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))
I got the following: {"x"=>15, "y"=>7}, which is a Ruby object. However in order to convert this to a Javascript object, I also needed to convert it to json.
So by taking it one step further, I am able to parse it into json like so:
Put require 'json' in the .rb file, and then do {"x"=>15, "y"=>7}.to_json which will result in
"{\"x\":15,\"y\":7}".
The reason you're not able to convert to JSON because hash rocket is not a proper JSON syntax. Hash rocket is purely Ruby syntax.
What that means is that you somehow managed to take a Hash and convert it to a String. So the converted string is actually Ruby code and not JSON.
You could do...
eval("{\"x\"=>15, \"y\"=>7}")
... and it will return a Ruby Hash.
Or if you don't want to use eval due to security reasons, you can do...
JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))

Nashorn/Rhino to convert a string from Java to Javascript

I'm using Play Framework and I have a .java Controller file in which I obtain an array of strings. I want to pass this Java array into an html file that will use Javascript in order to plot the data using Flot Charts. This data "transfer" is done in the render. It is something like this:
String[] array = new String[list.size()];
int i = 0;
for (Sample sample : list) {
array[i++] = sample.getContent();
}
render(array);
But then when I'm unable to call this variable in the .html file inside the views folder. If I use ${array}, Firebug tells me that it does not recognize it as a valid JS String array. I've read that Rhino or Nashorn could do the trick, but I do not know if they are the best and simplest option. Any ideas? Thanks!
I'm not familiar with Play Framework but I'm doing similar stuff using SparkJava in both java and javascript (using Nashorn).
I would suggest to use Boon library to generate json: https://github.com/boonproject/boon.
Here's a small Nashorn snippet to get you up to speed, easily adaptable to java:
// 1st we create a factory to serialize json out
var jso = new org.boon.json.JsonSerializerFactory().create();
// 2nd we directly use boon on array variable. Boon supports out of the box many pure java objects
jso.serialize(o);
In your specific case, you'll need to configure Play output for that particular render as application/json and possibly use render(jso.serialize(o)); in place of the small snippet I gave.

supplying initialization json string as parameter to jquery method

i have just begun using jquery datatables in my project and I do like it so far. I have many tables, sometimes 2-3 on a page. Rather than have to keep track of what initialization string I am using for a specific table and trying to remember what webpage its on, I have built an xml file to store all the initialization strings. I built some jquery functions to retrieve the strings on document ready but it never dawned on me how to actually inject the json into the method as a parameter.
If i was doing it manually you would call
selector.dataTables(json initializer string here);
Once I have that string how do I actually inject it into the method call? Or do I have to create that whole code line and inject it into my script?
If the json data comes in as something like this:
{"order": [[ 3, "desc" ]]}
You could use jquery to get the JSON via a HTTP GET request.
$.getJSON('somejson.json',function(data){
someSelector.dataTables(data)
});
Because you are using getJSON it will expect the JSON to be in that format and do the parsing for you.
Or if the JSON is available already(since you are using jquery you can use it to parse the JSON data just in case there may be a browser support issue since IE7 and below does not support JSON.parse.):
var options = $.parseJSON(someData);
someSelector.dataTables(options)
you can assign the json string to a variable...
var tableSettings = theJsonString;
selector.dataTables(tableSettings);
you may need to convert the string to an object first...
//javascript
var tableSettings = JSON.parse(theJsonString);
//jquery
var tableSettings = $.parseJSON(theJsonString);

How to make IF statement in Javascript based on the json result in PHP

Well, sorry for my bad grammar, but any help will be much appreciated..
Ok, here I'm trying to encode string by using json inside PHP then using JavaScript to read the json string. It will have 2 cases here.
The first one is, the application will running normally, so does the encode. The json string will be like this :
{"employee":
[{"id":"1","firstName":"aaa","lastName":"abc","timeIn":"08:00:00","timeOut":"17:00:00"},
{"id":"2","firstName":"bbb","lastName":"def","timeIn":"08:00:00","timeOut":"16:45:00"}]}
and the second one is, the PHP can't read the MySQL database, so in PHP the json encode will be like this :
{"errorProcess":{"text":SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. }}
The question is, in JavaScript how can I make an IF statement in JavaScript based on the result string in json?
Maybe it will be like this, but I don't know how to write it in JavaScript.
IF (in json string has employee){then result}
else if(in json string has errorProcess){then result}
Thanks for your help
You can check for errorProcess key using
if(json.hasOwnProperty('errorProcess')){
//do struff
}
JSON keys and values are accessed using dot (.) notation in Javascript. Assuming you already have the JSON as an object (not a string), you can simply write
if (json.employee) {
// do something
}
else if (json.error) {
// do something else
}
where json is a variable referencing your returned JSON from the php.
If your JSON is still in string format, you need to parse it into an object. This can be done with the built in JSON object.
var json = JSON.parse(jsonAsString);
First you need to parese JSON like this
var jsonObject= jQuery.parseJSON(yourJsonObj);
if(jsonObject.hasOwnProperty('employee')){
// Add your code
}else if(jsonObject.hasOwnProperty('errorProcess')){
// Add your code
}

Does anyone recogonize this format?

I saw this string from an ajax call on some. It's clearly some sort of template. a:15 means there're 15 items in the {} expression. i:0 means item0, s:63: means the length of the string after it. I google for a while, but could not find any JS template engine that can take input like this one. It is possible they use Regex to parse the data.
a:15:{i:0;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9fu2s0j20dw08v0v4.jpg\";i:1;s:63:\"http://ww4.some.web/mw600/c01b8166jw1e4cf9h284bj20dw0980ut.jpg\";i:2;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9ksczrj20dw097n20.jpg\";i:3;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9jvzymj20dw09840f.jpg\";i:4;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9m9j9rj20dw0av41i.jpg\";i:5;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9n1iq2j20dw0990ue.jpg\";i:6;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9q062tj20dw09en17.jpg\";i:7;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9sprglj20dw0a1djh.jpg\";i:8;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9srts5j20dw097jui.jpg\";i:9;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9wj84oj20dw08zn02.jpg\";i:10;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9ws795j20dw09o418.jpg\";i:11;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9xpixhj20dw0990ty.jpg\";i:12;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cfa05o8fj20dw099die.jpg\";i:13;s:63:\"http://ww4.some.web/mw600/c01b8166jw1e4cfa0ah9yj20dw0aa76h.jpg\";i:14;s:63:\"http://ww3.some.web/mw600/c01b8166jw1ehttp://ww2.some.web/mw600/c01b8166jw1e4cf9fu2s0j20dw08v0v4.jpgcfa1jpsaj20dw099myq.jpg\";}
Looks like result of PHP serialize() function
You can use this js function to parse it.
This is PHP serialization format. You can unserialize with php:
unserialize(...)
And you'll get an array (with your example) if I'm not wrong

Categories