I have a Person class that has a to_json method defined:
class Person
...
def to_json
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}.to_json
end
end
In another class I'm working with an array of Person objects. How can I return this array as a long chunk of valid JSON data? I've tried defining to_json in this new class like so:
class Directory
...
def to_json
@people.map do |person|
person.to_json
end.to_json
end
end
But this is is giving me some sort of strange looking thing with a bunch of " and \ characters scattered throughout the JSON data like this:
["{\"last_name\":\"Dole\",\"first_name\":\"Bob\",\"gender\":\"M\",\"favorite_color\":\"Red\",\"date_of_birth\":\"01/02/1950\"}","{\"last_name\":\"Man\",\"first_name\":\"Bean\",\"gender\":\"M\",\"favorite_color\":\"Blue\",\"date_of_birth\":\"04/03/1951\"}","{\"last_name\":\"Man\",\"first_name\":\"Green\",\"gender\":\"F\",\"favorite_color\":\"Yellow\",\"date_of_birth\":\"02/15/1955\"}","{\"last_name\":\"Clinton\",\"first_name\":\"Bill\",\"gender\":\"M\",\"favorite_color\":\"Orange\",\"date_of_birth\":\"02/23/1960\"}"]
whereas calling to_json on one Person is nicely formatted:
{"last_name":"Bob","first_name":"Hob","gender":"M","favorite_color":"red","date_of_birth":"01/01/2000"}