Skip to Content
Course content

23: Working with JSON and YAML in Ruby

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this a lot when developers first start dealing with external data: they assume that because JSON and YAML look like Ruby Hashes, they are Ruby Hashes. Specifically, there is a common belief that if you serialize a custom Ruby object into JSON and then parse it back, you'll get your original object back, complete with its methods and class identity.

Let's look at why that's a dangerous assumption. Imagine you have a Player class with a method called level_up!. You save the player to a JSON file and load it back later.

require 'json'

class Player
  attr_accessor :name, :xp
  def initialize(name, xp)
    @name = name
    @xp = xp
  end

  def level_up!
    @xp += 100
    puts "#{@name} leveled up!"
  end
end

hero = Player.new("Link", 500)
json_data = hero.to_json # Serializing to JSON
parsed_hero = JSON.parse(json_data)

puts parsed_hero.class # Output: String (or Hash, depending on the serializer)
# parsed_hero.level_up! # This would throw a NoMethodError

The Myth of the Automatic Object vs. The Reality of Generic Data

What happened here? JSON doesn't know what a Player class is. It only knows strings, numbers, booleans, arrays, and objects (which Ruby maps to Hashes). When you call JSON.parse, Ruby gives you a Hash containing the data, but the behavior—the methods you wrote in your class—is gone. You aren't holding a Player object; you're holding a bag of data that happens to have the same keys as your Player attributes.

To fix this, you have to manually "rehydrate" your object. I usually do this by adding a factory method to the class that takes a hash as an argument and returns a new instance.

class Player
  # ... existing code ...
  def self.from_json(json_string)
    data = JSON.parse(json_string)
    new(data["name"], data["xp"])
  end
end

# Now this works:
hero = Player.from_json(json_data)
hero.level_up! # "Link leveled up!"

Streaming Data with the JSON Library

JSON is the gold standard for APIs because it's lightweight and every language on earth understands it. In Ruby, the json library is your primary tool. While JSON.parse is what you'll use 90% of the time, don't forget JSON.generate (or .to_json) for the opposite direction.

One pro tip: if you're parsing an API response and you prefer symbols over strings for keys, pass the symbolize_names: true option. It makes your code feel much more "Ruby-ish" and prevents you from accidentally mixing data["name"] and data[:name] in the same file.

raw_response = '{"status": "success", "count": 42}'
data = JSON.parse(raw_response, symbolize_names: true)
puts data[:status] # "success"

Managing Configs with YAML

If JSON is for machines, YAML is for humans. You've probably seen .yml files in Rails projects for database configurations. YAML is far more flexible—it supports multi-line strings and comments—but it's slower to parse than JSON. Because of this, I never use YAML for high-frequency data transfer; I only use it for configuration files.

Ruby's yaml library (which is actually a wrapper around the Psych engine) makes this easy. You'll mostly use YAML.load_file to read a config and YAML.dump to write one.

require 'yaml'

app_config = {
  "settings" => {
    "theme" => "dark",
    "notifications" => true,
    "api_endpoint" => "https://api.example.com"
  }
}

# Writing to a file
File.write("config.yml", YAML.dump(app_config))

# Reading from a file
config = YAML.load_file("config.yml")
puts config["settings"]["theme"] # "dark"

Just a word of caution: be careful with YAML.load when dealing with untrusted user input. YAML can be used to instantiate arbitrary Ruby classes, which can lead to remote code execution vulnerabilities. Always use YAML.safe_load or YAML.load_file (which is safe in modern Ruby versions) when you aren't 100% sure where the file came from.




📋 Practical Task

Exercise: Building a Game Character Save-and-Load System

You are building a simple RPG character manager. Your goal is to create a system that loads default settings from a YAML file and saves the final character state to a JSON file.

Requirements:

  • Create a file named defaults.yml with the following content:
    base_stats:
      strength: 10
      agility: 10
      intelligence: 10
      starting_gold: 50
  • Write a Ruby script that:
    1. Loads the defaults.yml file.
    2. Creates a Character class that takes a name and the base_stats from the YAML file.
    3. Adds a method to the Character class called modify_stat(stat, amount) to increase or decrease a specific stat.
    4. Instantiates a character, modifies at least two of their stats, and then serializes the entire character object (including their name and updated stats) into a file called save_slot_1.json.
  • Verify that the save_slot_1.json file contains the updated values, not the defaults.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.