views:

79

answers:

3
var gallery = new TGallery([[{"image":{"updated_at":"2010-03-20T00:00:00Z","title":"dfgdfg","spam_reports":0,"by_profile_id":1,"comment_count":0,"id":1,"description":"htt","on_type":"profile","adult_reports":0,"on_id":1,"created_at":"2010-03-20T00:00:00Z"}]]);

Then in the TGallery class I would like to convert the json object to a js object. thanks

without a plugin if is possible... :)

A: 

That is already a "JS object". Just try accessing the argument in TGallery and you'll see.

Matti Virkkunen
thanks ;) heheh so stupid i was
Totty
A: 

You're already passing in a JavaScript object in that example. If you had a JSON string instead, you could do the following:

If you're using jQuery >= 1.4.1 you can use its built-in parseJSON method to turn your JSON string into an object. Otherwise, you'll want to use the library from JSON.org.

Jimmy Cuadra
I'm sure there's a really good reason not to, but what's wrong with good old eval?
spender
@spender `eval` will execute the string as code exactly as written. Using a JSON parser will verify that the string conforms to the JSON format which protects your script from various security implications, which have been thoroughly documented around the web.
Jimmy Cuadra
If the "JSON" is from a trusted source, eval() does not introduce any security holes, however I personally prefer to treat eval as evil all the time.
Matti Virkkunen
+1  A: 

What you posted isn't quite valid (missing a }), but if you can change the format a bit, no need for conversion, something like this:

var gallery = [{"image":{"updated_at":"2010-03-20T00:00:00Z","title":"dfgdfg","spam_reports":0,"by_profile_id":1,"comment_count":0,"id":1,"description":"htt","on_type":"profile","adult_reports":0,"on_id":1,"created_at":"2010-03-20T00:00:00Z"}}];

Changes here: added the closing brace, removed the extra [] wrapper and removed the TGallery() call. Then you can loop though/access images like this:

$.each(gallery, function(i, o) {
    alert(o.image.updated_at);
});​
Nick Craver
thanks for this tip. I will use in my app ;) really good
Totty