{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Difference between put and println in Ruby with examples

How to check a string contains a substring in Ruby with examples

How to check if element exists in hash or not in Ruby with examples

How to check if an element exists in Array or not in Ruby with examples

How to check if the variable is defined in Ruby with examples

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example