ruby · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
writes hashes and arrays as plain text.
A file can only hold text, but your data lives in hashes and arrays. JSON is a way to write that data as text, and almost every app and website understands it. Ruby's JSON tools are not loaded at the start, so write first.
.to_json turns a hash or array into a JSON string. does the reverse: it will parse JSON text and build the hash again. Keys come back as strings, unless you add symbolize_names: true.
JSON.pretty_generate writes the same text spread over lines, which is nicer to read in a file.
require "json"
pet = { name: "Rex", age: 3, tricks: ["sit", "roll"] }
puts pet.to_json
File.write("pet.json", JSON.pretty_generate(pet))
puts File.read("pet.json")
back = JSON.parse(File.read("pet.json"), symbolize_names: true)
p back[:tricks] JSON always wraps keys and strings in double quotes.
guess first
Strings or symbols? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
require "json"
text = { name: "Mia", score: 12 }.to_json
data = JSON.parse(text)
p data["score"]
p data[:score]
your turn
Your turn. Save your favourite things.
Fill in your favourite food, colour and number. The hash is saved as JSON, then loaded back.
fix it
Ruby has never heard of JSON. Can you fix it?
- Read the error. Ruby has no method called
to_json. Where do the JSON tools come from? - The JSON tools are not loaded when a program starts. You have to ask for them.
- Add require "json" as the very first line, then press run.
nailed it
your data can travel as text now. :D
require "json"loads the JSON tools..to_jsonmakes text.JSON.parsemakes data again.- Add
symbolize_names: trueto get symbol keys back.
new words in your collection
- JSON
- require
- parse
This lesson isn’t saved. A free account remembers every lesson you finish.