How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

Sometimes, We want to convert Hash object to JSON object in Ruby language.

Convert User-defined class objects into a JSON object in Ruby?

First, create an class with fields defined two methods

  • asJson - Convert the class into a hash object
  • toJSON - function convert a hash object into JSOn object using json
  • import json library using require call.

Here is a code

require 'json'

class Employee
    attr_accessor :name, :id,:salary
    def as_json(options={})
        {
            name: @name,
            id: @id,
               salary: @salary
        }
    end
    def toJson(*options)
        as_json(*options).to_json(*options)
    end
end

e = Employee.new
e.name = "John"
e.id = 5
e.salary = 5000

puts e.toJson

Convert Hash into a JSON object in Ruby?

Hash contains keys and values import json object and call to_json function converted to a JSON object.

Here is an example

require 'json'
employees = {'frank' => 5000, 'Andrew' => 6000, 'Rocky' => 10000}
puts employees.to_json