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.
Sometimes, We want to convert Hash object to JSON object in Ruby language.
First, create an class with fields defined two methods
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
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
🧮 Tags
Recent posts
Learn Golang Tutorials - Rune Types Explained with examples How to display images in Hugo with examples | Hugo Image shortcode Nodejs package.json resolutions How to find Operating System username in NodeJS? How to convert Double to Integer or Integer to double in Dart| Flutter By ExampleRelated posts