Reading and Writing JSON
JSON.parse and generate.
Reading and Writing JSON is a free Ruby Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is JSON?
JSON (JavaScript Object Notation) is a lightweight text format for data exchange. It maps cleanly to Ruby hashes and arrays.
Require the json library to use it.
require 'json'
data = { name: 'Ruby', year: 1995 }
puts(JSON.generate(data))Parsing JSON Text
JSON.parse turns a JSON string into Ruby objects: objects become Hashes, arrays become Arrays.
require 'json'
text = '{"name":"Ruby","year":1995}'
h = JSON.parse(text)
puts(h['name'])
puts(h['year'])Generating JSON Text
JSON.generate (or to_json on objects) converts Ruby data into a compact JSON string.
require 'json'
arr = [1, 2, { ok: true }]
puts(arr.to_json)Pretty Printing
JSON.pretty_generate produces human-readable, indented JSON, ideal for config files and debugging.
require 'json'
data = { name: 'Ruby', tags: ['fun', 'oop'] }
puts(JSON.pretty_generate(data))Symbol Keys on Parse
By default parsed keys are Strings. Pass symbolize_names: true to get Symbol keys instead.
require 'json'
h = JSON.parse('{"name":"Ruby"}', symbolize_names: true)
puts(h[:name])Nested Structures
JSON supports nesting. Parsing rebuilds the full tree of Hashes and Arrays.
require 'json'
text = '{"user":{"name":"Ada","roles":["admin","dev"]}}'
h = JSON.parse(text)
puts(h['user']['name'])
puts(h['user']['roles'][1])Type Mapping
JSON types map to Ruby:
- object → Hash, array → Array
- string → String, number → Integer/Float
- true/false → true/false, null → nil
require 'json'
h = JSON.parse('{"a":1,"b":1.5,"c":null,"d":true}')
puts(h['a'].class)
puts(h['c'].inspect)Writing JSON to a File
Combine pretty_generate with File.write to save data to disk.
require 'json'
require 'tmpdir'
path = File.join(Dir.tmpdir, 'data.json')
File.write(path, JSON.pretty_generate({ ok: true }))
puts(File.read(path))Reading JSON from a File
Read the file's contents and parse them in one step.
require 'json'
require 'tmpdir'
path = File.join(Dir.tmpdir, 'cfg.json')
File.write(path, '{"port":8081}')
cfg = JSON.parse(File.read(path))
puts(cfg['port'])Handling Parse Errors
Malformed JSON raises JSON::ParserError. Rescue it to handle bad input gracefully.
require 'json'
begin
JSON.parse('{not valid}')
rescue JSON::ParserError => e
puts 'Invalid JSON caught'
endRound Trip
Generating then parsing should return equivalent data, a useful sanity check.
require 'json'
original = { id: 7, tags: ['a', 'b'] }
back = JSON.parse(original.to_json, symbolize_names: true)
puts(back == original)Quick Check
Which option makes JSON.parse return Symbol keys instead of String keys?
Recap: Reading and Writing JSON
You can move data in and out of JSON:
JSON.parsestring to Ruby objectsto_json/JSON.generateto compact JSONpretty_generatefor readable outputsymbolize_names: truefor Symbol keys- Rescue
JSON::ParserErroron bad input
require 'json'
puts(JSON.parse('[1,2,3]').sum)Frequently asked questions
Is the “Reading and Writing JSON” lesson free?
Yes — the full text of “Reading and Writing JSON” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.
What will I learn in “Reading and Writing JSON”?
JSON.parse and generate. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Ruby Academy?
No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Reading and Writing JSON” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Ruby Academy lesson?
Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Reading and Writing JSON
- Working with CSV
- YAML Configuration
- Choosing a Format