×

ruby · level 2 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.