"category": "code-generator",
JSON to Ruby Class Generator
"tldr": Paste JSON and get Ruby classes with attr_reader and hash-based initializers - typed structure instead of nested hash access.
Paste a JSON payload and get plain Ruby classes with attr_reader accessors and initializers that construct nested objects and arrays of objects from the parsed hash - so instead of data.dig("customer", "name") scattered through the code, you write order.customer.name.
Wrapping parsed JSON in classes gives you a single place to document the shape, a natural home for domain methods, and NoMethodError at the right layer when the API changes - instead of silent nils propagating from deep hash access.
How to convert JSON to Ruby classes
- 1Paste a representative JSON payload into the input panel.
- 2snake_case attr_readers are generated from the JSON keys.
- 3Nested objects and arrays of objects are constructed recursively in the initializer.
- 4Instantiate with Root.new(JSON.parse(payload)).
Convert JSON to Ruby class in code
require "json"
order = Root.new(JSON.parse(payload))
puts order.customer.name
puts order.items.first.skurequire "net/http"
response = Net::HTTP.get(URI("https://api.example.com/orders/1042"))
order = Root.new(JSON.parse(response))Frequently asked questions
Why plain classes instead of OpenStruct or Struct?
OpenStruct is slow and hides typos (any method returns nil); Struct with keyword_init is decent but flattens poorly for nesting. Plain classes are fast, explicit about the shape, and give you a place for validation and domain logic. In Rails apps, consider dry-struct for typed attributes.
Can I make the attributes symbols instead of strings?
The initializers read string keys because JSON.parse produces string-keyed hashes by default. If you parse with symbolize_names: true, change the initializers to attributes[:key] - pick one convention and keep it consistent.
How do I add validation?
Raise in the initializer for required fields: raise ArgumentError, "order_id required" unless attributes["order_id"]. For serious contracts, define a JSON Schema with our generator and validate with the json_schemer gem before constructing objects.
What about serializing back to JSON?
Add a to_h method returning the hash shape and Ruby's to_json handles the rest: def to_h = { "order_id" => order_id, ... }. Or include ActiveModel::Serializers::JSON in Rails for conventions.
Last updated:
You might also need
Free and in-browser, like everything on JSON Console. Browse all tools →