I\'m trying to understand the JSON serialization landscape in Ruby. I\'m new to Ruby.
Is there any good JSON serialization options if you are not working with Rails?
Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.
# suppose we have a sample object as below
sampleObj.name #=> foo
sampleObj.last_name #=> bar
# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
json.name sampleObj.name
json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"
require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"
To get the build in classes (like Array and Hash) to support as_json
and to_json
, you need to require 'json/add/core'
(see the readme for details)
If rendering performance is critical, you might also want to look at yajl-ruby, which is a binding to the C yajl library. The serialization API for that one looks like:
require 'yajl'
Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"
Check out Oj. There are gotchas when it comes to converting any old object to JSON, but Oj can do it.
require 'oj'
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
a = A.new
puts Oj::dump a, :indent => 2
This outputs:
{
"^o":"A",
"a":[
1,
2,
3
],
"b":"hello"
}
Note that ^o
is used to designate the object's class, and is there to aid deserialization. To omit ^o
, use :compat
mode:
puts Oj::dump a, :indent => 2, :mode => :compat
Output:
{
"a":[
1,
2,
3
],
"b":"hello"
}
Since I searched a lot myself to serialize a Ruby Object to json:
require 'json'
class User
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def as_json(options={})
{
name: @name,
age: @age
}
end
def to_json(*options)
as_json(*options).to_json(*options)
end
end
user = User.new("Foo Bar", 42)
puts user.to_json #=> {"name":"Foo Bar","age":42}