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?
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
To use the 'json' library:
require 'json'
To convert an object to JSON (these 3 ways are equivalent):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
To convert JSON text to an object (these 2 ways are equivalent):
JSON.load string #returns an object
JSON.parse string #returns an object
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\""
.
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:
class A
def to_json
{'a' => @a, 'b' => @b}.to_json
end
def self.from_json string
data = JSON.load string
self.new data['a'], data['b']
end
end
You could automate this by inheriting from a 'JSONable' class:
class JSONable
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
def from_json! string
JSON.load(string).each do |var, val|
self.instance_variable_set var, val
end
end
end
Then you can use object.to_json
to serialise to JSON and object.from_json! string
to copy the saved state that was saved as the JSON string to the object.
What version of Ruby are you using? ruby -v
will tell you.
If it's 1.9.2, JSON is included in the standard library.
If you're on 1.8.something then do gem install json
and it'll install. Then, in your code do:
require 'rubygems'
require 'json'
Then append to_json
to an object and you're good to go:
asdf = {'a' => 'b'} #=> {"a"=>"b"}
asdf.to_json #=> "{"a":"b"}"
I used to virtus
. Really powerful tool, allows to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, possible to create objects from ruby hashes, there is strict mode. Check it out.
Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.
If you're using 1.9.2 or above, you can convert hashes and arrays to nested JSON objects just using to_json.
{a: [1,2,3], b: 4}.to_json
In Rails, you can call to_json on Active Record objects. You can pass :include and :only parameters to control the output:
@user.to_json only: [:name, :email]
You can also call to_json on AR relations, like so:
User.order("id DESC").limit(10).to_json
You don't need to import anything and it all works exactly as you'd hope.