to_json problems with objects/hashes
Reported by Jonah Fox | June 9th, 2009 @ 04:19 AM
I had trouble converting RubyLand proxies into JSON. One problem is converting array's "[1,1]" ends up as "1,1" if you use 'json' library. This is fixed by using ActiveSupport instead.
The other problem was converting Objects into Hashes and also seeing the difference between an Object and an Array.
The following code kinda provides a to_json method - it's a bit ugly (particularily the check against '[Object]', but seems to work :
module Johnson #:nodoc:
module SpiderMonkey #:nodoc:
class RubyLandProxy # native
def to_json(arg=nil)
RubyLandProxy.to_json(self)
end
def RubyLandProxy.to_json proxy
ret = nil
if proxy.to_s == "[object Object]"
ret = {}
proxy.each do |k,v|
ret[k] = (v.class == RubyLandProxy) ? RubyLandProxy.to_json(v) : v
end
else
ret = []
i = 0
proxy.each do |v|
ret[i] = (v.class == RubyLandProxy) ? RubyLandProxy.to_json(v) : v
i += 1
end
end
ret.to_json
end
end
end end
Comments and changes to this ticket
-
Jonah Fox June 9th, 2009 @ 04:23 AM
actually that was slightly incorrect - here's an updated version
module Johnson
module SpiderMonkeyclass RubyLandProxy def to_json(arg=nil) RubyLandProxy.to_json(self) end def RubyLandProxy.to_jsonable_object proxy ret = nil if proxy.to_s == "[object Object]" ret = {} proxy.each do |k,v| ret[k] = (v.class == RubyLandProxy) ? RubyLandProxy.to_jsonable_object(v) : v end else ret = [] i = 0 proxy.each do |v| ret[i] = (v.class == RubyLandProxy) ? RubyLandProxy.to_jsonable_object(v) : v i += 1 end end ret end def RubyLandProxy.to_json proxy RubyLandProxy.to_jsonable_object(proxy).to_json end end
end end
-
John Barnette June 23rd, 2009 @ 07:32 PM
- State changed from new to resolved
Please Sign in or create a free account to add a new ticket.
With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป