Why isn't my ruby class converting to json? -


i confused why simple ruby object not converting json.

>irb > require 'json'  class user   attr_accessor :name, :age    def initialize(name, age)     @name = name     @age = age   end end  u1 = user.new("a", 1) u2 = user.new("b", 2)  puts u1.to_json "\"#<user:0x000001010e9f78>\"" 

what missing?

i want store these objects array collection, , convert entire collection json.

users = [] users << user.new("a", 1) users << user.new("b", 2)  users.to_json 

note: not using rails, plain old ruby!

i want json array of user objects.

[ {"name": "john", "age": 22}, {"name": "john1", "age": 23} {"name": "john2", "age": 24} ] 

by default, classes cannot made json strings. must have to_json method in class, can make inherit class (type class user < jsonable):

class jsonable     def to_json         hash = {}         self.instance_variables.each |x|             hash[x] = self.instance_variable_get x         end         return hash.to_json     end end 

then, can call to_json , work properly.


test:

$ irb

irb(main):001:0> require 'json' => true irb(main):002:0> class jsonable irb(main):003:1>     def to_json irb(main):004:2>         hash = {} irb(main):005:2>         self.instance_variables.each |x| irb(main):006:3*             hash[x] = self.instance_variable_get x irb(main):007:3>         end irb(main):008:2>         return hash.to_json irb(main):009:2>     end irb(main):010:1> end => nil irb(main):011:0> class user < jsonable irb(main):012:1>  attr_accessor :name, :age irb(main):013:1>  irb(main):014:1*   def initialize(name, age) irb(main):015:2>     @name = name irb(main):016:2>     @age = age irb(main):017:2>   end irb(main):018:1> end => nil irb(main):019:0>  irb(main):020:0* user = user.new("hi",3) => #<user:0x007fd6c8af0a90 @name="hi", @age=3> irb(main):021:0> puts user.to_json {"@name":"hi","@age":3} 

Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -