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?
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"
}