Convert user object to JSON using JSON gem

I am learning how to parse and generate JSON with a pearl of JSON. I can easily create a hash of data and generate it in JSON; however, I have a brain fart when it comes to taking an instance of a class (like an instance of Person) and translating all of its instance variables inside the hash into JSON.

Here is an example that I came across:

require "json"

class Person

  def initialize(name, age, address)
    @name = name
    @age = age
    @address = address
  end

  def to_json

  end


end

p = Person.new('John Doe', 46, "123 Elm Street")
p.to_json

.to_json, person JSON. , , Person, , JSON.generate(hash). , . - to_json , , ? !

+5
1

, :

def to_json(*a)
  {
    'json_class'   => self.class.name,
    'data'         => Your data
  }.to_json(*a)
end

json_class JSON , . *a , JSON-, , hash to_json. :

    'data'         => [@name, @age, @address]

    'data'         => { 'name' => @name, 'age' => @age, 'address' => @address

self.json_create, , - JSON.

+11

All Articles