0

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Santhosh S
  • 1,141
  • 6
  • 21
  • 43
  • 3
    If you're going to do it manually, then use normal string manipulation to remove leading `@` from the symbols (which are symbols; that's a hint you'd want to convert it to a string). There are a ton of libraries that'll do all this for you, though. – Dave Newton Sep 05 '15 at 16:32

2 Answers2

2

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"}
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

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)

Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • I do not want to use additional libraries. Preferably would like to do with ruby +json libs Thanks ! – Santhosh S Sep 05 '15 at 18:22
  • Okay, that may not be trivial task - even default Ruby implementation of `JSON#generate` (conveniently) deals with hash-like objects. But, it will be fun - so, have fun! – Wand Maker Sep 05 '15 at 19:43