Ruby objects and JSON serialization (without Rails)

I am trying to understand the landscape of JSON serialization in Ruby. I am new to Ruby.

Are there any good JSON serialization options if you are not working with Rails?

This answer seems to go (to Rails) How to convert a Ruby object to JSON

It seems that json gem looks like you should write your own to_json method. I was not able to get to_json to work with arrays and hashes (the documentation says that it works with them) Is there a reason why json gem does not just reflect the object and uses the default serialization strategy? Isn't that how to_yaml works (guessing here)

+62
json ruby serialization jsonserializer
Dec 16 '10 at 18:19
source share
11 answers

In order for the JSON library to be available, you may have to install libjson-ruby from the package manager.

To use the json library:

 require 'json' 

To convert an object to JSON (these three methods 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 two methods are equivalent):

 JSON.load string #returns an object JSON.parse string #returns an object 

It will be a little harder for objects from your own classes. For the next class, to_json will create something like "\"#<A:0xb76e5728>\"" .

 class A def initialize a=[1,2,3], b='hello' @a = a @b = b end end 

This is probably undesirable. To effectively serialize your object as JSON, you must create your own to_json method. To do this, it is useful to use the from_json class method. You can expand your class as follows:

 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 can automate this by inheriting the '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 serialize to JSON and object.from_json! string object.from_json! string to copy the saved state that was saved as the JSON string for the object.

+96
Dec 16 '10 at 19:42
source share

If rendering performance is critical, you can also look at yajl-ruby , which is a link to C yajl . The serialization API for this is as follows:

 require 'yajl' Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}" 
+8
Dec 16 '10 at 19:30
source share

Check out Oj . There are problems 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 

It is output:

 { "^o":"A", "a":[ 1, 2, 3 ], "b":"hello" } 

Note that ^o used to indicate the class of an object and exists to support deserialization. To omit ^o , use :compat mode:

 puts Oj::dump a, :indent => 2, :mode => :compat 

Output:

 { "a":[ 1, 2, 3 ], "b":"hello" } 
+8
Jun 19 '13 at 3:10
source share

What version of Ruby are you using? ruby -v will tell you.

If it is 1.9.2, JSON is included in the standard library .

If you are on 1.8. Something, then gem install json and it will be installed. Then in your code do:

 require 'rubygems' require 'json' 

Then add to_json to the object and you will go well:

 asdf = {'a' => 'b'} #=> {"a"=>"b"} asdf.to_json #=> "{"a":"b"}" 
+6
Dec 16 '10 at
source share
 require 'json' {"foo" => "bar"}.to_json # => "{\"foo\":\"bar\"}" 
+3
Dec 16 '10 at 18:22
source share

Since I searched many times to serialize a Ruby Object for 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} 
+3
Aug 02 '16 at 10:49 on
source share

If you use 1.9.2 or higher, you can convert hashes and arrays to nested JSON objects using to_json.

 {a: [1,2,3], b: 4}.to_json 

In Rails, you can call to_json in Active Record objects. You can pass: include and: only parameters for controlling the output:

 @user.to_json only: [:name, :email] 

You can also call to_json over AR relationships, for example:

 User.order("id DESC").limit(10).to_json 

You do not need to import anything, and everything works as you hope.

+1
May 10 '13 at 9:37
source share

To get the assembly in classes (e.g. Array and Hash) to support as_json and to_json , you need require 'json/add/core' (see readme for details)

+1
Apr 05 '15 at 13:47 on
source share

Jbuilder is a gem created by the rails community. But it works well in non-rail environments and has a cool feature set.

 # 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\"}" 
+1
Sep 25 '16 at 9:49
source share

There is actually a gem called Jsonable, https://github.com/treeder/jsonable . It is very cute.

0
Nov 13 '14 at 11:24
source share

I used virtus . A really powerful tool that allows you to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, the ability to create objects from ruby ​​hashes, there is a strict mode. Check it out.

0
Jan 15 '16 at 23:44
source share



All Articles