Reputation: 17160
I am learning how to parse and generate JSON with the JSON gem. I am easily able to create a hash of data and generate that into JSON; however, I am having a brain fart when it comes to taking a instance of a class (such as a Person instance) and putting all of its instance variables inside a hash to be converted into JSON.
This is the example I am having trouble with:
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
I want to create a .to_json
method so that I can take a person object and have all of its instance variables converted into JSON. What I think I need to do is take all of the Person's instance variables, put them in a hash then call JSON.generate(hash)
. I am having a brain fart on how to do that right now. So can someone help me complete the to_json
method, or perhaps suggest a better way of implementing it? Thanks!
Upvotes: 5
Views: 3010
Reputation: 3589
First you need to make sure you use the right basic structure:
def to_json(*a)
{
'json_class' => self.class.name,
'data' => Your data
}.to_json(*a)
end
The json_class
key is used by the JSON gem to determine what class to pass the data to. The *a
parameter includes all the arguments that the JSON gem is passing in, generally unimportant for your classes so you just pass it straight on to the hash's to_json
call. Next the simplest ways to store your data are a hash or an array:
'data' => [@name, @age, @address]
or
'data' => { 'name' => @name, 'age' => @age, 'address' => @address
The first might be faster and makes the self.json_create
method slightly easier to write, while the second is a lot easier to make backward compatible if you ever change the data structure and wish to load old JSON objects.
Upvotes: 12