Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my ruby class converting to json?

Tags:

json

ruby

I am confused why my simple ruby object is not converting to json.

>irb
>
require 'json'

class User
  attr_accessor :name, :age

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

u1 = User.new("a", 1)
u2 = User.new("b", 2)

puts u1.to_json
"\"#<User:0x000001010e9f78>\""

What am I missing?

I want to then store these objects into an array collection, and then convert the entire collection to json.

users = []
users << User.new("a", 1)
users << User.new("b", 2)

users.to_json

Note: This is not using Rails, just plain old Ruby!

I want my json to be an array of user objects.

[
{"name": "john", "age": 22},
{"name": "john1", "age": 23}
{"name": "john2", "age": 24}
]
like image 501
Blankman Avatar asked Apr 25 '26 11:04

Blankman


1 Answers

The default implementation of to_json is quite simple and clearly is not doing what you would expect. And this is expected: you need to write code to explain to the interpreter how you want your program to behave.

It's a common standard to provide both a to_json and as_json method. The first latter returns a JSON-serializable version of the instance (generally a Hash), the latter is the actual JSON output.

class User
  attr_accessor :name, :age

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

  def as_json(*)
    { name: @name, age: @age }
  end

  def to_json(*)
    as_json.to_json()
  end
end

Here's the output

2.3.0 :034 > u1.as_json
 => {:name=>"a", :age=>1}
2.3.0 :035 > puts u1.to_json
{"name":"a","age":1}
 => nil

With a little effort you can change the as_json to automatically collect all the instance variables. However, I discourage this approach as you may end-up serializing sensitive attributes you don't really want to share (like passwords).

like image 57
Simone Carletti Avatar answered Apr 28 '26 02:04

Simone Carletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!