About the JSON to Ruby
Generate Ruby classes with keyword-argument constructors, a from_hash builder and to_h, or compact Struct definitions, all with snake_case attribute names.
Key features
- Ruby classes with keyword-argument constructors
- from_hash builders that construct nested objects
- to_h methods that restore the original JSON keys
- Or compact Struct definitions (keyword_init)
- snake_case attributes; Ruby keywords made safe
- Optional values default to nil
Ruby objects from JSON
Ruby makes it easy to dig through JSON.parse hashes, but hash["customer"]["address"]["city"] gets fragile fast. Generate plain Ruby classes with readable attributes, a from_hash builder and to_h.
Example
{ "id": 1001, "price": 9.5, "tags": ["gift"], "customer": { "name": "Ada" }, "coupon": null }
class Order
attr_accessor :id, :price, :tags, :customer, :coupon
def initialize(id:, price:, tags:, customer:, coupon: nil)
@id = id
@price = price
@tags = tags
@customer = customer
@coupon = coupon
end
def self.from_hash(h)
new(
id: h['id'],
price: h['price'],
tags: h['tags'],
customer: Customer.from_hash(h['customer']),
coupon: h['coupon'],
)
end
def to_h
{ 'id' => @id, 'price' => @price, 'tags' => @tags, 'customer' => @customer&.to_h, 'coupon' => @coupon }
end
end
order = Order.from_hash(JSON.parse(response.body))
order.customer.name # => "Ada"
Struct mode
Order = Struct.new(:id, :price, :tags, :customer, :coupon, keyword_init: true)
Struct mode is ideal for flat data: Order.new(**JSON.parse(json, symbolize_names: true)). The keys must match the member names, and nested hashes stay hashes.
Tips
- Ruby 3.2+: consider
Data.define(...)for immutable value objects. - Type checking: add RBS or Sorbet signatures using the attribute types shown in your JSON.
- Serialization:
JSON.generate(order.to_h)turns objects back into JSON.
Related tools
Generating for another dynamic language? See JSON to Python or JSON to Elixir.
How to use the JSON to Ruby
- Paste your data into the input box, upload a file, or click Sample to try it out.
- Adjust the options above the editor if you need to (indentation, delimiter, and so on).
- The Ruby appears instantly in the output panel. Any errors are shown with their line and column.
- Click Copy to copy the result, or Download to save it as a file.