2

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"}

1 Answer 1

3

The code is converting array of strings (json string), not array of hashes.

Instead of using Person#to_json in Directory#to_json, use Person#to_hash like following:

class Person
  def to_hash
    {
      last_name: @last_name,
      first_name: @first_name,
      gender: @gender,
      favorite_color: @favorite_color,
      date_of_birth: @date_of_birth
    }
  end

  def to_json
    to_hash.to_json
  end
end



class Directory
  def to_json
    @people.map do |person|
      person.to_hash
    end.to_json
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.