In ruby:
class Obj
attr_accessor :price
end
my_ruby_obj = Obj.new
puts my_ruby_obj.to_json
"\"#<Obj:0x1c9b018>\""
Server sends my_ruby_obj.to_json to browser (sinatra, with content_type :json) in response to a jquery ajax request (with $.get), which correctly defines a return type of json, and launches a callback function(data) which does:
console.log(data);
which returns:
#<Obj:0x1c9b018>
Now how do I access "data.price" attribute in javascript/jquery as I would normally do on a ruby object to access its attribute? ("my_ruby_obj.price")
I tried with console.log(data.price);
> Undefined
I feel I am missing a big piece here.. and I guess it has to do with how json works with objects..
Any help ? If possible, I'm looking for a correct way to do it with jquery.
Thanks
edit: trying to understand what is going on, I tried this in the callback:
newdata = $.parseJSON(data);
but debug console halts on it showing:
> uncaught exception: Invalid JSON: #<Obj:0x1c9b018>
I did call .to_json on the ruby object, so why it says so? ...
[[new_edit:]]
Seems like ruby json serialization for objects from custom classes is not working as I supposed:
Quoting from here: https://stackoverflow.com/a/4464721/988591
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like
"\"#<A:0xb76e5728>\""
. This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method.
and examples are following... But.. wow... isn't there an easier way ?