Reputation: 1159
I am trying to create an object and convert it to json.
require 'json'
class Person
attr_accessor :first_name, :last_name
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
end
person = Person.new
person.first_name = "Michael"
person.last_name = "Jordon"
I get the output:
person.to_json
# => {"@first_name":"Michael","@last_name":"Jordon"}
What's the change I have to make so that the @
symbol does not come as part of variable names in json string?
Upvotes: 0
Views: 2006
Reputation: 110665
Just change the line:
hash[var] = self.instance_variable_get var
to:
hash[var.to_s[1..-1]] = self.instance_variable_get var
You'll get:
puts person.to_json
#=> {"first_name":"Michael","last_name":"Jordon"}
Upvotes: 2
Reputation: 18762
You can use Rails Active Support JSON extension
require 'active_support/json'
class Person
attr_accessor :first_name, :last_name
end
person = Person.new
person.first_name = "Michael"
person.last_name = "Jordon"
puts ActiveSupport::JSON.encode(person)
# {"first_name":"Michael","last_name":"Jordon"}
More options explained here - Ruby objects and JSON serialization (without Rails)
Upvotes: 1