From: "Matthias S." Date: 2011-02-10T00:42:55+09:00 Subject: Best practice to create a JSON string of one object containing an array of other objects using Ruby? What is a good practice to create a JSON string of one object (object of class A) containing an array of objects (objects of class B)? I am particularly interessted in the implementation of class's A to_json method. Assuming class A looks as follows: class A attr_accessor :items def initialize() @items = Array.new end def to_json(*a) ?SECRET OF THE DAY? end end and class B: class B def to_json(*a) {"class B" => "class B"}.to_json(*a) end end The best solution I got so far is: def to_json(*a) json = Array.new @items.each do |item| json << item.to_json(*a) end {"class A" => json}.to_json(*a) end Assuming there is only one item in array of an object of class A, the resulting JSON string looks as follows: {"class A":["{\"class B\":\"class B\"}"]} I also tried: def to_json(*a) {"class A" => @items}.to_json(*a) end But it results in IOError exception in class A, saying to_json "not opened for reading"... I am sure we can do better? -- Posted via http://www.ruby-forum.com/.