I'm trying to serialize a JavaScript object to json, to be deserialized later back into its original form.
The hard part is that it's not just primitives I need to serialize. For example:
function Foo() {
this.bar = "Hello World";
}
Foo.prototype.baz = function() {
alert(this.bar);
}
var qux = new Foo();
How would I serialize qux? If I simply JSON.stringify then JSON.parse it, I wouldn't be able to call qux.baz().
Are there any standards or tools or techniques out there to do this? Any tips to point me in the right direction?
Thanks.
JavaScript object to JSON
Unfortunately you cannot serialize your complete object to JSON since the JSON spec does not allow functions to be serialized.
You can however create your own serialization standard. You can call it Javascript Frozen Object (JSFO) which is a good name since in other languages what you're trying to do is usually called "freezing". Or if you want a name similar to JSON you can call it Javascript Frozen (or Full?) Object Notation (JSFON).
The implementation is fairly straightforward. You can copy the JSON code from any of the libraries that implement it like jQuery or YUI. Or you can download any of the reference implementation from json.org and modify it to stringify functions as well.
To stringify functions you basically need to do something like this:
if (typeof obj == 'function') {
return '"' + key + '":' + obj.toString();
}
plug something like that into any of the JSON stringification libraries.
But please don't call it JSON since JSON is a very specific data format with a published specification.
I'd start looking at the JSON documentation on MDN, specifically JSON.stringify.
Related
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"
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.
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
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