JSON to Ruby Class Generator

Generate Ruby classes with attr_accessor, Struct, ActiveModel, or Dry-Struct support from JSON. Includes from_json and to_json methods.

What is JSON to Ruby Class Generator?

This tool converts JSON data into Ruby classes with proper type inference, attr_accessor declarations, and serialization methods. It supports Plain Ruby, Struct, ActiveModel, and Dry-Struct frameworks.

How to Use

  1. Set the root class name and choose a framework (Plain Ruby, Struct, ActiveModel, or Dry-Struct)
  2. Paste your JSON data into the input area
  3. Click "Generate Ruby Code" and copy the output into your project

Why Use This Tool?

Automatically infer Ruby types from JSON values (String, Integer, Float, TrueClass, Array)
Generate from_json and to_json methods for seamless serialization
ActiveModel mode includes validations and serialization support
Dry-Struct mode generates type-safe immutable value objects
Nested objects are converted to separate Ruby classes

Tips & Best Practices

  • Use realistic sample data — type inference depends on actual values
  • ActiveModel mode generates presence validations for non-nil fields
  • Dry-Struct mode uses the dry-struct gem with Types module for type safety
  • Enable Symbolize Keys to use Ruby symbols instead of string keys in from_json
  • The Require JSON option adds the require 'json' header at the top of the output

Frequently Asked Questions

What is ActiveModel mode?

ActiveModel mode generates classes that include ActiveModel::Serialization and ActiveModel::Validations. It provides attr_accessor for all fields, an initialize method that accepts keyword arguments, and presence validations for non-nil fields. The serializable_hash method handles serialization.

How are JSON types mapped to Ruby?

JSON strings → String, integers → Integer, decimals → Float, booleans → TrueClass, null → NilClass (nullable), arrays → Array, nested objects → separate Ruby classes. In Dry-Struct mode, types use Types::String, Types::Integer, Types::Float, Types::Bool, etc.

What is Dry-Struct mode?

Dry-Struct mode generates classes that inherit from Dry::Struct. Attributes are defined using the Types module (e.g., attribute :name, Types::String). Dry-Struct provides immutable, type-safe objects with built-in validation and coercion. It requires the dry-struct gem.

How are nested objects handled?

Nested JSON objects are converted to separate Ruby classes. They are ordered children-first, so nested classes appear before the parent class that references them. The parent class calls the nested class's from_json_hash and to_hash methods for serialization.

Is my data sent to a server?

No, all processing happens entirely in your browser. Your JSON data never leaves your device.

Related Tools