Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

to_json problems with objects/hashes

#51

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

Reported by Jonah Fox · June 9th, 2009 @ 04:19 AM

State: resolved
Milestone: none
Assigned to: John Barnette John Barnette

Activity

  1. Jonah Fox
    Jonah Fox

    actually that was slightly incorrect - here's an updated version

    module Johnson
    module SpiderMonkey

    class 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

    June 9th, 2009 @ 04:23 AM

  2. John Barnette

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.