Best practice to create a JSON string of one object containing an array of other objects using Ruby? -
what practice create json string of 1 object (object of class a) containing array of objects (objects of class b)? particularly interessted in implementation of class's to_json method.
assuming class looks follows:
class attr_accessor :items def initialize() @items = array.new end def to_json(*a) ?secret of day? end end
and class b:
class b def to_json(*a) {"class b" => "class b"}.to_json(*a) end end
the best solution got far is:
def to_json(*a) json = array.new @items.each |item| json << item.to_json(*a) end {"class a" => json}.to_json(*a) end
assuming there 1 item in array of object of class a, resulting json string looks follows:
{"class a":["{\"class b\":\"class b\"}"]}
i sure can better?
i instead
def to_json(*a) {"class a" => @items}.to_json(*a) end
the problem approach @items
array contains strings, not objects. in case to_json create array of strings, not array of objects.
Comments
Post a Comment