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 ?
Ok I found exactly what I was looking for! An automated quick solution, which also comes with other side benefits (more speed!).
The standard json gem only works for some classes (Array, Hash,..) and can’t translate a custom class/object you have created to JSON. It doesn’t know how to organize data, unless you write yourself a custom .to_json method for your class, which is what I was tring to avoid..
So in the end I found a gem called Oj: Optimized Json (gem install oj)
Quoting the authors:
I used it like so:
json = Oj.dump(guy, mode: :object)but in my case it worked without mode: :object as well.now
console.log(data);shows:Now that the serialization is working good, I can finally do:
console.log(data.age);// —> 50Serialization is faster too.
..It has been a long ride though 😉
A big Thank You goes to the library author: http://twitter.com/#!/peterohler