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"
Related
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
Why can't I parse the JSON object? I need to wrap it in quotes for parse to work.
// JSON object
var foo = {"sayHi": {"nl":"hoi", "en":"hello"}};
alert(foo.sayHi.en);
// string
var foo = '{"sayHi": {"nl":"hoi", "en":"hello"}}';
alert(JSON.parse(foo).sayHi.nl);
edit:
// does not work
var foo = {"sayHi": {"nl":"hoi", "en":"hello"}};
alert(JSON.parse(foo).sayHi.nl);
Yes, both work, but the first foo doesn't work the with parse. And I like the first foo better, because I don't need to worry about linebreaks, quotes and plus signs.
edit2:
I'm really looking for a nice way to store the JSON in a variable instead of using an ajax call to get it.
Because this {"sayHi": {"nl":"hoi", "en":"hello"}} is already js object
and this '{"sayHi": {"nl":"hoi", "en":"hello"}}' is just a string, containing whatever, maybe json
Depends on what you mean by "parse the JSON object" (which is not a thing by the way; JSON is a notation). If you want to parse it into an object then congratulations, you're done! JSON.parse takes a string using JSON (the notation) and turns it into an object in JavaScript (but many other languages can also parse JSON and turn it into respective data structures).
Both of your code snippets work as expected, though.
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);
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
Duplicate: Converting HTML TAG Object to JSON Object
Hi,
Is there is any Javascript API that converts complex Javascript Objects To JSON String???
I don't think what you're looking for a an API per se. That would be a something like a service where you send data and receive back something else.
What you want is called a serializer. It turns a javascript object into a string of text representing the object-literal. For example:
var foo = {};
foo[bar] = "baz";
//do serializing to get a -string- that looks like this:
{bar: "baz"}
That way when a service receives this JSON information, if it uses javascript, it's already in a format where it can be read directly into memory without conversion. Here is an example javascript serializer:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx