JSON to Ruby: classes that read JSON.parse output and write it back
Paste a sample API response and get Ruby classes with named accessors instead of digging through nested hashes.
Paste or upload your JSON
Start with real JSON data, ideally a response where every field is filled in. The comments in the output come from the values you paste, so a list with several items describes the fields better than a single one.
Example: try this JSON
{
"userId": 12345,
"username": "rubyist",
"email": "[email protected]",
"isActive": true,
"preferences": ["convention_over_configuration", "dont_repeat_yourself"],
"profile": {
"firstName": "Yukihiro",
"lastName": "Matsumoto",
"age": 30,
"country": "Japan"
}
}Pick the class name and options
Three settings sit above the editors, and the output changes as soon as you touch one.
Read the generated classes
All classes go into one file. from_h reads each key by its original name, so userId lands in user_id, and to_h puts the original names back.
Output for the example above (first class)
require 'json'
# Read JSON into objects with:
# data = Root.from_json(json)
# and write it back with data.to_json.
class Root
attr_accessor :user_id # Integer, JSON key "userId"
attr_accessor :username # String
attr_accessor :email # String
attr_accessor :is_active # Boolean, JSON key "isActive"
attr_accessor :preferences # Array<String>
attr_accessor :profile # Profile
def initialize(user_id: nil, username: nil, email: nil, is_active: nil, preferences: nil, profile: nil)
@user_id = user_id
@username = username
@email = email
@is_active = is_active
@preferences = preferences
@profile = profile
end
# Builds a Root from the Hash that JSON.parse returns (string keys, as in the JSON).
def self.from_h(hash)
return nil if hash.nil?
new(
user_id: hash['userId'],
username: hash['username'],
email: hash['email'],
is_active: hash['isActive'],
preferences: hash['preferences'],
profile: Profile.from_h(hash['profile'])
)
end
def self.from_json(json)
from_h(JSON.parse(json))
end
def to_h
{
'userId' => @user_id,
'username' => @username,
'email' => @email,
'isActive' => @is_active,
'preferences' => @preferences,
'profile' => @profile&.to_h
}
end
def to_json(*args)
to_h.to_json(*args)
end
end
# ... then class Profile, built the same wayCopy or download the Ruby file
Save the file in your project, require it and load the data.
What is JSON to Ruby Conversion?
JSON.parse gives you nested hashes with string keys, so every read is data['profile']['firstName'] and a typo just returns nil. Small classes with named accessors make the shape of the data visible and let data.profile.first_name read like the rest of your Ruby.
Writing those classes by hand for a big API response is tedious, so this page writes them from a real sample. Check the JSON first with the JSON Validator if it came from a log, or use XML to Ruby when your data arrives as XML.
Frequently Asked Questions
How do I load JSON into the generated classes?
Call Root.from_json(json) with the raw JSON text. It runs JSON.parse and hands the Hash to Root.from_h, which builds the object and turns nested objects and lists of objects into the nested classes. If you already have the Hash, for example params in a Rails controller turned into a plain Hash, call Root.from_h(hash) directly. data.to_h gives you a Hash with the original JSON keys again, and data.to_json writes the JSON back out.
Do I need any gems?
No. The code is plain Ruby and only uses the json library that ships with Ruby, so require 'json' is all it needs. It was checked with Ruby 3.3, and nothing in it is specific to Rails, so it works the same in a script, a Sinatra app or a Rails project.
Will long IDs like 8901240544102066246 stay exact?
Yes. Ruby's Integer has no size limit and JSON.parse reads whole numbers as Integers, so an ID like 8901240544102066246 keeps every digit on the way in and on the way out. Numbers written with a decimal point or exponent, like 14.50 or 1e3, become Floats, so 14.50 is written back as 14.5 (the same value). Quoted text such as "00501" stays a String with its leading zeros.
Why are the types only in comments?
Ruby doesn't declare types on attributes, so each attr_accessor line carries a comment saying what the field holds, worked out from every item of your lists: Integer, Float, String, Boolean, a nested class or Array<...>. A field that is missing from some items or null in any of them says ", nil". The one thing the code does enforce is Float: a field that mixes 3 and 14.5 gets to_f in from_h, so you always get a Float back.
How are JSON keys turned into Ruby names?
Keys become snake_case, so "planId" turns into plan_id. A key that is a Ruby keyword or would replace a method every object needs, like class, end or hash, gets an underscore at the end (class_). Keys that start with a digit get a field_ prefix, and two keys that land on the same name, like "first_name" and "firstName", are kept apart with _2. Nested class names never reuse core names such as String or Hash. from_h and to_h always use the original keys, so the JSON reads and writes correctly.
What if my JSON is a list?
The class is built from every item of the list merged together, so a field that only some items have still gets an accessor. The comment at the top of the file shows how to read it: JSON.parse(json).map { |item| Root.from_h(item) }, and items.map(&:to_h).to_json to write it back.
Is my JSON sent anywhere?
No. The classes are built in your browser as you type, and nothing you paste or upload is sent to our server or kept after you leave the page.