Printing JSON object from javascript function on glassfish server log - javascript

Scenario: Java servlet running on glassfish 4.1/jdk1.8.45. There is a javascript function being read from Database and executed on server side using javax.script.*. When trying to debug this function, it is desired to output some json objects on server log.It is printing [Object object] instead of the actual JSON.Tried using JSON.stringify(), it gives[undefined].
Is there a way to print the actual contents on the json object in this scenario?
Thanks.

JSON.stringify works only javascript objects. It does not work on Java objects. Please make sure that you're calling JSON.stringify on a JavaScript object.
If you do need to make JSON string on a java object, you can use Object.bindProperties extension (https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties) to bind properties of the Java object to a script object and then call JSON.stringify on the same.
Sample (test) code is here -> http://hg.openjdk.java.net/jdk9/dev/nashorn/file/0de67a63e2c7/test/script/nosecurity/treeapi/utils.js
This script is used to convert a Nashorn AST tree object [a Java object] as friendly JSON object.

If you want to use JSON.stringify and it gives undefined, does it mean JSON is undefined or just the function?
If so, it may be that Nashorn doesn't have it in the box. Maybe try and add it as a polyfill: you can have a look here or here.

If you are dealing with strings in the Nashorn scripting engine then there is a probability they are Java strings rather than javascript strings. The fix is to convert your Java strings to Javascript strings.
// this string does not work with stringify()
var javaString = someMethodReturningAJavaString();
var jsString = new String(javaString);
// now stringify() works:
var myJson = JSON.stringify({'key': jsString});
If typeof(new String(javaString)) returns object rather than string then use new String(javaString).valueOf(). For some values this seems to be the only solution with Mozilla's Rhino js engine.
If you have numbers then you might need to wrap java objects in the the new Number() constructors.
For details on the Nashorn engine have a look at https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html

Related

From Gson to javascript

It seems everyones using Gson to get JSON from a javascript file or just to exchange JSON in Java classes. I'm trying to send a Gson object to a javascript file but I'm not sure how to get the attributes from the Gson object inside my javascript file. I haven't found any tutorial explain something like that. I'd love to see a tutorial somewhere or have someone explain me how I should do this. I haven't used Gson before.
JSON, whose name means JavaScript Object Notation, was designed to be easy to parse in JavaScript.
Historically you could use eval for that but now there's a dedicated function in all browsers : JSON.parse : pass it your JSON string and it will return an object or an array.
Note that many libraries helping you query the server from a script running in a browser will also do the parsing for you so that you don't even have to call JSON.parse.
dystroy is right.
Assuming you have read your GSON/JSON object into a javascript string, JSON.parse will create an object for you.
E.G.:
var myString = '{"firstName":"John","lastName":"Doe","nickName":"Johnny","title":"Mr","emailAddresses":["johndoe#example.com","john#example.com"]}'
var myObject = JSON.parse(myString);
// now we have an object with properties
console.log(myObject.firstName); // logs "John"
console.log(myObject.emailAddresses[1]); // logs "john#example.com"

Passing RegExp objects between content scripts and main add-on script

I am having an issue whereby I create a RegExp object in a content script and pass it as part of an object back to the main script using self.port.emit().
Somewhere along the way it seems to lose its identity as a RegExp and also its toString abilities. The following returns false in the main script, but true in the content script:
Object.prototype.toString.call(regexp) == '[object RegExp]';
regexp instanceof RegExp;
Interestingly for Arrays passed in the same way the following is true:
Object.prototype.toString.call(array) == '[object Array]';
Am I missing something?
The Add-on SDK doesn't pass objects around when you send messages, only strings - it essentially calls JSON.stringify() on one side and then JSON.parse() on the other. The result is easy to predict:
console.log(JSON.stringify(new RegExp()));
This gives you "{}". In other words, JSON.stringify() treats "custom" objects as normal objects without any properties, object prototypes and such are ignored. What you get in your main code is a plain object, same as if you call new Object().
If you need to pass a regular expression to your main code - send regexp.source, create an actual regular expression on the other side. Sending actual objects around isn't possible.
What about if you just sent the regex pattern instead of the whole rexexp object? e.g. encodeURIComponent(regexp.source);

Check what holds in [object Object] in jQuery

I am using a jQuery plugin which returns the object, for example using the below code.
onSuccess: function(data, status){
alert(data);
}
returns [object Object]
as it is returning the object i would like to know how do i check all the contents that holds inside that object using js alert();
also i would like to know if JS object and JSON are one and the same.
thank you
Use proper debugging tools like Firebug for Firefox or the built in Chrome developer tools. Then you can inspect objects with console.log or console.dir.
alert is not meant for debugging. It can only output strings, which is of limited use as you already noticed.
also i would like to know if JS object and JSON are one and the same.
No, they are not. JSON is a data exchange format, similar to what XML can be used for, whereas a JavaScript object is a data type in JavaScript.
If you are wondering whether JavaScript object literals are JSON, then this answer has to be answered with no as well.
These are object literals
var foo = {foo: "bar"};
var foo = {"foo": "bar"};
whereas JSON can only exist inside strings in JavaScript:
var foo = '{"foo": "bar"}';
and which then has to be parsed into a equivalent JavaScript data type. This is done by parsers such as the built-in JSON or json2.js.
Don't let their similar syntax/structure fool you.
For the first part of your question, check this: How to Loop through plain JavaScript object with objects as members?
And for your second question regarding json and js object: No, json is a string representation of a data structure, read here: http://en.wikipedia.org/wiki/JSON. However, it easy to parse a json to a js object.
Check this .data( key, value ) or .data( obj )
where
key - A string naming the piece of data to set.
value -The new data value; it can be any Javascript type including Array or Object.
obj - An object of key-value pairs of data to update.
OR
You can also use jQuery.each

How to get Javascript Objects from JavaScriptSerializer?

When I use the System.Web.Script.Serialization.JavaScriptSerializer.Serialize method, I get back valid JSON code.
This is usually perfect, but sometimes I want to get back the result as a Javascript object, not JSON. The Serialize method has an overload that takes a SerializationFormat parameter. That looks perfect... but it is marked as internal!
How can I get out a string of Javascript from the Serializer?
Take a look at the JScript DLL Eval object's JScriptEvaluate method (http://msdn.microsoft.com/en-us/library/microsoft.jscript.eval.jscriptevaluate.aspx):
using Microsoft.JScript;
var MyJSObject = Eval.JScriptEvaluate("{a:'Property1',b:'Property2'}", Engine);

Converting JSONobj to Obj not working?

I'm attempting to convert a JSON object to a "normal" object using the following...
var slaobj = eval('('+s+')');
s being the JSON. however, it doesnt seem to work (It's `.length' is coming back as undefined). What am I doing wrong?
It's `.length' is coming back as undefined
It won't necessarily have a length property, unless it's an array or some other object that has one. For example:
var json = '{"foo": "Value of foo"}';
var obj = eval('(' + json + ')');
alert(obj.foo); // alerts "value of foo"
alert(obj.length); // alerts "undefined", there's no `length` in `obj`
Live example
Off-topic: Using eval to deserialize JSON text can be a security problem, unless you can unambiguously trust the source of the JSON text (for instance, it's your own server and you're connecting via SSL), because eval doesn't parse JSON, it parses and runs JavaScript code. (Adding the parentheses doesn't really help.) You can get alternatives to using eval from Douglas Crockford's Github page (he's the inventor of JSON). Last I checked, there are three alternatives there, two of which don't use eval at all; see the README at the bottom of the page for details.
Objects don't all have ".length" properties. An object literal like:
{ 'foo': 100, 'bar': 'Abraham Lincoln' }
describes an object that has no ".length" property.
JavaScript Array objects have ".length" properties because of the way the language runtime works. But a plain object in JavaScript only has such a property if you put it there.
How are you retrieving the object?
I would say there has to be something else wrong - are you sure the 's' JSON object was returned correctly?
JSON.org
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
Update: Ah, I see, that's what the parentheses are for. Rats. Deleted the first part.
But this remains valid:
Don't use eval!
eval() is a dangerous function, which
executes the code it's passed with the
privileges of the caller. If you run
eval() with a string that could be
affected by a malicious party, you may
end up running malicious code on the
user's machine with the permissions of
your webpage / extension. More
importantly, third party code can see
the scope in which eval() was invoked,
which can lead to possible attacks in
ways of which the similar Function is
not susceptible.
Source: Mozilla JavaScript Reference: eval()
http://www.jsonlint.com/ this site has good JSON string validation which you should have at your disposal all the times. It's good to validate the JSON string when its really big.
Also do not user the eval() to get the JSON object. Visit http://www.json.org/ it has really nice guide lines check it.
There are many JavaScript libraries today which offers JSON API. I will suggest you to user one of it for safety.
http://api.jquery.com/jQuery.getJSON/
http://developer.yahoo.com/yui/json/
http://dojotoolkit.org/reference-guide/dojo/_base/json.html

Categories

Resources