JSON in Ruby: JSON.parse and to_json in Practice

Ruby has JSON support in its standard library through the json module, which needs to be explicitly required (but doesn’t require any gem installation on modern Ruby versions, since it’s part of the standard library). This post covers the basics of parsing and generating JSON, plus a very Ruby-specific feature: the to_json method available directly on objects.

Requiring the library

require 'json'

Converting JSON into a Ruby object

# ruby on rails
json_text = '{"name": "Ana", "age": 30}'
data = JSON.parse(json_text)

puts data["name"] # Ana
puts data.class # Hash

JSON.parse() converts the JSON string into a Ruby Hash. A JSON array becomes a Ruby Array, following the same principle.

Converting keys to symbols

By default, the keys in the resulting Hash are strings. If you’d rather work with symbols (more idiomatic in Ruby), pass the symbolize_names option.

# ruby on rails
data = JSON.parse(json_text, symbolize_names: true)

puts data[:name] # Ana, now accessible via symbol

Converting a Ruby object into JSON

# ruby on rails
data = { name: "Ana", age: 30 }
json_text = data.to_json

puts json_text # {"name":"Ana","age":30}

Here’s Ruby’s quirk: unlike Python or PHP, where you call a function from the JSON module to convert (json.dumps(), json_encode()), in Ruby the to_json method is available directly on the object itself, once you’ve required the json library. This works on Hash, Array, String, Integer, and other basic types.

# ruby on rails
[1, 2, 3].to_json # "[1,2,3]"
"test".to_json # "\"test\""

There’s also an equivalent form using the module directly, if you prefer that style.

# ruby on rails
JSON.generate(data) # same as data.to_json

Formatting the output JSON (pretty print)

# ruby on rails
data = { name: "Ana", address: { city: "New York" } }

puts JSON.pretty_generate(data)

JSON.pretty_generate() formats the JSON with readable indentation. There’s no equivalent to_json with built-in indentation; for that, you use this specific module method.

Handling parse errors

# ruby on rails
begin
  data = JSON.parse('{"name": "Ana",}') # trailing comma, invalid
rescue JSON::ParserError => error
  puts "Error parsing JSON: #{error.message}"
end

JSON::ParserError is the exception raised when parsing fails, following Ruby’s begin/rescue pattern (equivalent to try/catch in other languages).

Working with custom objects (classes)

If you want your own class to convert to JSON automatically, define the to_json method on it.

# ruby on rails
class Person
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def to_json(*args)
    { name: @name, age: @age }.to_json(*args)
  end
end

person = Person.new("Ana", 30)
puts person.to_json # {"name":"Ana","age":30}

This gives you full control over how serialization happens, including omitting fields or renaming keys, similar to what annotations do in other languages, just through an explicit method instead of declarative metadata.

Quick checklist

  • Did you remember require 'json' at the top of the file?
  • Did you decide between string keys or symbol keys (symbolize_names: true) consistently across the project?
  • Using JSON.pretty_generate() when you need readable output, since to_json alone doesn’t format it?
  • Handling JSON::ParserError in code that receives JSON from external sources?

To quickly validate a JSON before using it in your Ruby code, paste it into JSON Validator.