TExcelTAD
Home › Ruby › Ruby JSON

Ruby JSON

JSON (JavaScript Object Notation) is the most common format for exchanging data between programs and web APIs. Ruby's standard library includes the json library, which converts between JSON text and Ruby hashes, arrays, strings, numbers, true/false and nil.

Parsing JSON

JSON.parse turns a JSON string into Ruby objects:

ruby · try it yourself
require "json"

text = '{"name": "Kaito", "age": 29, "skills": ["ruby", "sql"], "remote": true, "manager": null}'
data = JSON.parse(text)

p data
p data["name"]
p data["skills"].first
p data["manager"]
p data.class
{"name" => "Kaito", "age" => 29, "skills" => ["ruby", "sql"], "remote" => true, "manager" => nil}
"Kaito"
"ruby"
nil
Hash
JSON Ruby
object {...} Hash
array [...] Array
string String
number Integer or Float
true / false true / false
null nil

Symbol keys

By default, object keys become strings. Pass symbolize_names: true to get symbols, which is often nicer in Ruby code (and required for hash pattern matching):

ruby · try it yourself
require "json"

json = '{"city": "Porto", "temp": 21.5, "tags": ["sunny"]}'
weather = JSON.parse(json, symbolize_names: true)
p weather
puts "#{weather[:city]}: #{weather[:temp]}°C"

case weather
in {city: String => city, temp: Float => t} if t > 20
  puts "Warm in #{city}"
end
{city: "Porto", temp: 21.5, tags: ["sunny"]}
Porto: 21.5°C
Warm in Porto

Generating JSON

Call to_json on a hash or array, or use JSON.generate. For readable output use JSON.pretty_generate:

ruby · try it yourself
require "json"

order = {id: 501, items: [{sku: "A1", qty: 2}, {sku: "B7", qty: 1}], paid: false, note: nil}

puts order.to_json
puts JSON.generate([1, "two", 3.0])
puts JSON.pretty_generate(order)
{"id":501,"items":[{"sku":"A1","qty":2},{"sku":"B7","qty":1}],"paid":false,"note":null}
[1,"two",3.0]
{
  "id": 501,
  "items": [
    {
      "sku": "A1",
      "qty": 2
    },
    {
      "sku": "B7",
      "qty": 1
    }
  ],
  "paid": false,
  "note": null
}

Symbol keys are written as strings — JSON has no symbols. So a round trip JSON.parse(hash.to_json) gives you string keys back.

Invalid JSON

JSON.parse raises JSON::ParserError for malformed input. Always rescue it when the text comes from outside your program:

ruby · try it yourself
require "json"

["[1, 2, 3]", "{'single': 'quotes'}", '{"trailing": 1,}', ""].each do |input|
  value = JSON.parse(input)
  puts "ok: #{value.inspect}"
rescue JSON::ParserError
  puts "invalid JSON: #{input.inspect}"
end
ok: [1, 2, 3]
invalid JSON: "{'single': 'quotes'}"
invalid JSON: "{\"trailing\": 1,}"
invalid JSON: ""

Converting your own objects

Give your class a to_h and a to_json method that builds on it — and a class method to rebuild objects from parsed data:

ruby · try it yourself
require "json"

class Task
  attr_reader :title, :done

  def initialize(title, done = false)
    @title = title
    @done = done
  end

  def to_h = {title:, done:}
  def to_json(*args) = to_h.to_json(*args)

  def self.from_h(h) = new(h[:title], h[:done])
end

tasks = [Task.new("Write tests", true), Task.new("Deploy")]
json = JSON.generate(tasks)
puts json

restored = JSON.parse(json, symbolize_names: true).map { |h| Task.from_h(h) }
restored.each { |t| puts "[#{t.done ? 'x' : ' '}] #{t.title}" }
[{"title":"Write tests","done":true},{"title":"Deploy","done":false}]
[x] Write tests
[ ] Deploy

JSON.generate calls to_json on every object it meets, so Task objects inside an array are serialised automatically.

Saving and loading a JSON file

ruby · try it yourself
require "json"

settings = {theme: "dark", volume: 7, plugins: ["git", "lint"]}
File.write("settings.json", JSON.pretty_generate(settings))

loaded = JSON.parse(File.read("settings.json"), symbolize_names: true)
loaded[:volume] += 1
File.write("settings.json", JSON.pretty_generate(loaded))

p JSON.load_file("settings.json", symbolize_names: true)
{theme: "dark", volume: 8, plugins: ["git", "lint"]}

JSON.load_file reads and parses in one step.

Tip: Working with a deeply nested API response? Combine symbolize_names: true with dig (data.dig(:user, :address, :city)) or with pattern matching to pull out exactly what you need.

Test yourself

What Ruby value does JSON null become?

  1. null
  2. nil
  3. false
  4. "null"

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

  1. {a: 1}
  2. {"a" => 1}
  3. ["a", 1]
  4. A JSON object

Which exception does JSON.parse raise for malformed input?

  1. ArgumentError
  2. SyntaxError
  3. JSON::ParserError
  4. TypeError