Thuta Learning
Ruby
AdvancedProgrammingBeginner

Files & JSON

RubyLesson 2335 min

What you'll walk away with

  • Use File.write, File.read, File.readlines, File.foreach and block-form File.open where each fits
  • Tell apart "w" mode, which truncates, and "a" mode, which appends
  • Experiment with files cleanly using Dir.mktmpdir
  • Save and reload a Hash with JSON.generate, JSON.pretty_generate and JSON.parse(symbolize_names: true)
  • Know that JSON cannot round-trip symbols or Time, and handle Errno::ENOENT and JSON::ParserError

Explain it simply

Files and JSON in plain language

Variables vanish when a program ends. A file is a place that outlasts the program, and JSON is a text format that most languages and web services can read. Think of writing a note and putting it in a drawer: JSON.generate turns your Hash into the text of the note, File.write puts it in the drawer, and File.read plus JSON.parse take it out and rebuild the Hash.

Two habits keep this safe. Open files with a block so Ruby closes them even when something goes wrong, and use a temporary directory while learning so your experiments clean up after themselves.

Problem → Why → Solution

The problem: hand-built JSON breaks

A small tool stores each article as a line of text that looks like JSON, building the text by hand with string interpolation. Everything works until a title contains a double quote. The result {"title": "Say "hi""} is not valid JSON, the next JSON.parse raises JSON::ParserError, and the corrupted line is already saved in the file.

Hand-written JSON forgets other rules as well: backslashes, newlines, Unicode and numbers must all be escaped or formatted in specific ways. Reading has its own traps. A file that does not exist raises Errno::ENOENT, and a file that was only half written raises ParserError. A program that has not planned for both simply crashes.

hand_built_json.rb
require "json"

title = 'Say "hi"'
json = "{\"title\": \"#{title}\"}"   # hand-built JSON
puts json                               # {"title": "Say "hi""}
JSON.parse(json)                        # JSON::ParserError
puts JSON.generate({ title: title })    # {"title":"Say \"hi\""}

A library knows every rule

A JSON library knows every escaping and formatting rule, so it always produces valid text and you never concatenate it yourself. Block-form File.open also guarantees the file is closed even when something fails. So let JSON.generate build the text, handle the file with a block, and rescue the two failures you can expect.

Core concept: reading, writing and converting to JSON

File.write(path, text) creates or overwrites a file and returns the number of bytes written. File.read(path) returns the whole file as one String. For large files, File.foreach(path) hands you one line at a time without loading everything, and File.readlines(path, chomp: true) returns an array. For finer control use File.open(path, mode) { |file| ... }: when the block ends Ruby closes the file, even if an exception was raised inside.

The mode says how the file is opened. "r" reads and "w" writes, but "w" truncates the file the moment it opens, so the old contents are gone even if you write nothing. "a" appends to the end. Build paths with File.join(dir, name) rather than gluing strings with "dir/" + name, so they work on every operating system. Dir.mktmpdir { |dir| ... } creates a temporary directory and deletes it with everything inside when the block ends, which makes it ideal for experiments.

For JSON, begin with require "json". JSON.generate(object) produces compact text and JSON.pretty_generate(object) produces indented text that is easier for people to read (object.to_json matches generate). JSON.parse(text) returns a Hash whose keys are Strings; pass symbolize_names: true to get symbol keys (values are not changed). Invalid text raises JSON::ParserError, which descends from JSON::JSONError and then StandardError.

JSON does not support every Ruby type, so a round trip does not always give back what you started with. JSON has no symbol type, so symbol values become strings, and keys that are not Strings, such as 7, become strings too. nil becomes null and comes back as nil. Time turns into its to_s text, so if you want it back, write it with iso8601 and convert it again with Time.iso8601. NaN and Infinity raise JSON::GeneratorError.

MethodWhat it doesWatch out
File.write(path, text)Creates or overwrites the fileExisting contents are lost
File.read(path)The whole file as one StringA huge file fills memory
File.foreach(path)Yields one line at a timeEach line ends in \n; chomp it
File.open(path, "a") { }Appends, and closes when the block ends"w" truncates on open
Mental model: a note in a drawer
  1. Hash in memory
  2. JSON.generate -> String
  3. File.write puts it on disk
  4. File.read + JSON.parse brings it back

Every round trip can turn types JSON lacks (symbols, Time) into strings, so check what comes back.

General pattern

ruby
require "json"

File.write(path, JSON.pretty_generate(hash))                 # save
hash = JSON.parse(File.read(path), symbolize_names: true)    # load

File.open(path, "a") { |file| file.puts line }               # append
File.foreach(path) { |line| process(line.chomp) }            # stream lines

Dir.mktmpdir { |dir| path = File.join(dir, "name.json") }    # scratch space

The first two lines save and reload a Hash. The "a" mode of File.open appends and File.foreach reads one line at a time. The last line gives you scratch space for experiments.

Example: saving and reloading settings as JSON

This example saves a settings Hash as JSON inside a temporary directory, reads it back and checks that what returned equals what was saved. It then deliberately tries a missing file and a corrupted file and rescues both errors. The path is never printed, so the output is the same on every machine.

settings_json.rb
require "json"
require "tmpdir"

settings = { theme: "dark", font_size: 14, tags: ["ruby", "json"], beta: nil }

Dir.mktmpdir("settings-demo") do |dir|
  path = File.join(dir, "settings.json")

  File.write(path, JSON.pretty_generate(settings))
  puts File.read(path)

  loaded = JSON.parse(File.read(path), symbolize_names: true)
  puts loaded == settings
  puts loaded[:font_size] + 1

  begin
    File.read(File.join(dir, "missing.json"))
  rescue Errno::ENOENT => e
    puts "missing file: #{e.class}"
  end

  File.write(path, '{"theme": "dark"')
  begin
    JSON.parse(File.read(path))
  rescue JSON::ParserError
    puts "file is not valid JSON"
  end
end

Code breakdown

  1. Scratch directoryDir.mktmpdir("settings-demo") do |dir|

    It creates a temporary directory and deletes everything when the block ends, so no files are left behind. The returned path depends on the machine, so do not print it.

  2. SaveFile.write(path, JSON.pretty_generate(settings))

    The Hash becomes indented JSON text and is written to the file. pretty_generate keeps it readable for people, and in the output you can see nil turn into null.

  3. Loadloaded = JSON.parse(File.read(path), symbolize_names: true)

    The file is read as a String and JSON.parse turns it back into a Hash with symbol keys. Without symbolize_names, loaded[:theme] would be nil, because the keys would be strings such as "theme".

  4. The round tripputs loaded == settings

    It prints true because every value in settings (strings, an integer, an array, nil) exists in JSON. A symbol value such as theme: :dark would have made it false.

  5. Missing filerescue Errno::ENOENT => e

    Reading a missing file raises Errno::ENOENT. e.message includes the path, so the example prints only the class name, which is also a good habit when you do not want paths in logs.

  6. Corrupted filerescue JSON::ParserError

    A file containing a half-written {"theme": "dark" cannot be parsed. Rescuing ParserError lets the program report the corruption instead of crashing.

You should see
{
  "theme": "dark",
  "font_size": 14,
  "tags": [
    "ruby",
    "json"
  ],
  "beta": null
}
true
15
missing file: Errno::ENOENT
file is not valid JSON

Line by line, append mode and the danger of "w"

For files that only grow, such as logs, use "a" mode. The code below starts the file with File.write, which behaves like "w", then appends with puts, write and << in turn. File.foreach(path).with_index(1) pairs each line with its number, and chomp strips the trailing newline. At the end, reopening with "w" wipes everything that was there and leaves only "reset", which is one of the most common ways to lose data.

append_and_lines.rb
require "tmpdir"

Dir.mktmpdir("lines-demo") do |dir|
  path = File.join(dir, "app.log")

  File.write(path, "start\n")                        # "w": creates or overwrites
  File.open(path, "a") do |file|                     # "a": append
    file.puts "loaded config"
    file.write("ready\n")
    file << "stopped" << "\n"
  end

  File.foreach(path).with_index(1) do |line, number|
    puts "#{number}: #{line.chomp}"
  end

  p File.readlines(path, chomp: true).length          # 4
  p File.basename(path), File.extname(path)           # "app.log" ".log"

  File.open(path, "w") { |file| file.print "reset" }  # "w" truncates the file
  p File.read(path)                                   # "reset"
  p File.exist?(path), File.exist?(File.join(dir, "nope.log"))   # true false
end

What JSON cannot round-trip

The code below sends a Ruby hash through JSON and back and shows what changed. The symbol :active became the string "active", and the key 7 became "7", which prints as "7": even with symbolize_names. Time turned into its to_s text, so it is no longer a Time and the format is Ruby-specific, which is why you write iso8601 and convert with Time.iso8601 on the way back. Notice that comparing the original hash with the reloaded one gives false. For richer values (symbol values, Time, sets, your own objects), convert them with your own to_h on the way out and rebuild them on the way in.

json_round_trip.rb
require "json"
require "time"

moment = Time.utc(2024, 1, 2, 3, 4, 5)
original = { status: :active, count: 3, started: moment, 7 => "seven" }
text = JSON.generate(original)
puts text
# {"status":"active","count":3,"started":"2024-01-02 03:04:05 UTC","7":"seven"}

back = JSON.parse(text, symbolize_names: true)
p back
# {status: "active", count: 3, started: "2024-01-02 03:04:05 UTC", "7": "seven"}
p back[:status].class     # String
p back == original        # false

safe = JSON.generate({ started: moment.iso8601 })
puts safe                 # {"started":"2024-01-02T03:04:05Z"}
restored = Time.iso8601(JSON.parse(safe)["started"])
p restored == moment      # true

p JSON.parse("[1, 2.5, null, true]")    # [1, 2.5, nil, true]
p JSON.parse('{"a": 1}')[:a]            # nil: the key is the String "a"
begin
  JSON.generate(Float::NAN)
rescue JSON::GeneratorError
  puts "NaN cannot be written as JSON"
end

The p output of the hash (the back line) uses the Ruby 3.4-and-later style, and this output was produced with Ruby 4.0.9. Older versions print hash rockets, as in {:status=>"active"}, but the values inside are the same.

Loading safely, with defaults

A config file can be missing or corrupted, so the loading code should plan for both. The load_settings method below returns the defaults when the file is missing (Errno::ENOENT) and, when it is corrupt (JSON::ParserError), prints a notice and returns the defaults. When the file is valid, its values are merged over DEFAULTS, so missing keys fall back to the default. Notice that only two classes are rescued; other errors, such as a permission problem, stay loud.

load_with_defaults.rb
require "json"
require "tmpdir"

DEFAULTS = { theme: "light", font_size: 12 }.freeze

def load_settings(path)
  DEFAULTS.merge(JSON.parse(File.read(path), symbolize_names: true))
rescue Errno::ENOENT
  DEFAULTS.dup
rescue JSON::ParserError
  puts "settings file is corrupt, using defaults"
  DEFAULTS.dup
end

Dir.mktmpdir("settings") do |dir|
  path = File.join(dir, "settings.json")
  p load_settings(path)           # {theme: "light", font_size: 12}

  File.write(path, '{"theme": "dark"}')
  p load_settings(path)           # {theme: "dark", font_size: 12}

  File.write(path, "{oops")
  p load_settings(path)           # prints the notice, then the defaults
end

In real projects

Where this shows up in real projects

JSON appears in configuration files such as settings.json, in API payloads (calling JSON.parse on a response body from Net::HTTP, or Rails's render json:), and in JSON Lines logs where each line is one JSON object. In tests, Dir.mktmpdir and Tempfile create files cleanly and delete them afterwards, and fixtures are often written as JSON.

Production adds a few concerns. To avoid half-written files, write to a temporary file first and move it into place with File.rename (an atomic write). JSON's default encoding is UTF-8, so pass encoding: "UTF-8" explicitly when unsure. For input you do not control, prefer JSON.parse, because by default it builds only plain Ruby types; read the json gem's documentation before using JSON.load. And never commit JSON files that contain secrets such as API keys.

Common mistakes

Common mistakes

1. Using "w" when you meant "a"

Opening with File.open(path, "w") { }, even with an empty block, wipes the file, and File.read then returns "". Use "a" to add to what is there, and "w" only when replacing is truly what you want.

2. Reading with symbol keys but no symbolize_names

JSON.parse('{"a": 1}')[:a] is nil, because the key is the String "a". Since no error is raised, you meet a NoMethodError later and the trail is cold. Add symbolize_names: true when reading, or use string keys such as data["a"] consistently.

3. Assuming symbols and Time survive the trip

Saving { status: :active } and reading it back gives the value "active", so a check like == :active is false. Time turns into text as well. Check what type comes back, or choose an explicit format such as iso8601 when you save.

4. Opening a file without a block and never closing it

If you write f = File.open(path) and forget f.close, the handle stays open and buffered writes may not be flushed, and if an exception occurs in between, the closing code is never reached. Writing File.open(path) { |f| ... } lets Ruby do the closing and removes this mistake entirely.

Best practices

Best practices

  • Never concatenate JSON text yourself; use JSON.generate or to_json.
  • Use block forms (File.open, File.write, File.read) and build paths with File.join.
  • When reading, rescue Errno::ENOENT and JSON::ParserError specifically and say clearly what went wrong.
  • Use Dir.mktmpdir for experiments and tests, and keep absolute paths out of prints and logs.

Mini challenge

Mini challenge: a contacts book

Write two helpers that save a contact list to a JSON file and load it back. A missing file gives an empty list, and a corrupt file raises a clear error.

  • load_contacts(path) reads with JSON.parse(..., symbolize_names: true) and returns [] when the file is missing
  • Invalid JSON raises ArgumentError "contacts file is corrupt"
  • save_contacts(path, contacts) writes pretty JSON to the file
  • Inside Dir.mktmpdir: start empty, add two contacts and save, reload and print the sorted names, then overwrite the file with broken JSON and show the error message
contacts.rb
require "json"
require "tmpdir"

def load_contacts(path)
  # TODO: parse the file with symbol keys
  # TODO: a missing file means an empty list
  # TODO: invalid JSON becomes ArgumentError "contacts file is corrupt"
end

def save_contacts(path, contacts)
  # TODO: write pretty JSON
end

# TODO: inside Dir.mktmpdir: load (empty), add two contacts, save, reload and print
# TODO: overwrite the file with broken JSON and show the error message

Expected: Expected output: 0 contacts at start 2 contacts after reload: Aye, Ko corrupt file: contacts file is corrupt

Show hint

A method body can carry rescue Errno::ENOENT and rescue JSON::ParserError directly at its end, with no begin. To test the corrupt case, overwrite the file with File.write(path, "[{").

Show solution
contacts.rb
require "json"
require "tmpdir"

def load_contacts(path)
  JSON.parse(File.read(path), symbolize_names: true)
rescue Errno::ENOENT
  []
rescue JSON::ParserError
  raise ArgumentError, "contacts file is corrupt"
end

def save_contacts(path, contacts)
  File.write(path, JSON.pretty_generate(contacts))
end

Dir.mktmpdir("contacts") do |dir|
  path = File.join(dir, "contacts.json")

  contacts = load_contacts(path)
  puts "#{contacts.length} contacts at start"

  contacts << { name: "Ko", phone: "0912" }
  contacts << { name: "Aye", phone: "0933" }
  save_contacts(path, contacts)

  reloaded = load_contacts(path)
  names = reloaded.map { |contact| contact[:name] }.sort
  puts "#{reloaded.length} contacts after reload: #{names.join(", ")}"

  File.write(path, "[{")
  begin
    load_contacts(path)
  rescue ArgumentError => e
    puts "corrupt file: #{e.message}"
  end
end

Quick quiz 1 / 3

What does JSON.parse('{"a": 1}')[:a] return?

Quick quiz 2 / 3

A file already contains "one\n". After File.open(path, "w") { }, what does File.read(path) return?

Quick quiz 3 / 3

What is JSON.parse(JSON.generate({ status: :active }), symbolize_names: true)[:status]?

What to remember

  • Handle files with File.write, File.read, File.foreach and block-form File.open; "w" truncates on open and "a" appends.
  • Dir.mktmpdir creates a temporary directory and removes it when the block ends, keeping experiments clean; never print the path.
  • JSON.generate and pretty_generate turn a Hash into text and JSON.parse brings it back; add symbolize_names: true for symbol keys.
  • JSON cannot give back symbols or Time, and Errno::ENOENT and JSON::ParserError should be rescued specifically.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.