JSON

Added in v1.9 · Updated March 13, 2026 · Modules
ruby stdlib json

The JSON module provides utilities for parsing and generating JSON data. It’s part of Ruby’s standard library, so you don’t need to install anything extra.

Overview

JSON (JavaScript Object Notation) is a lightweight data interchange format. Ruby’s JSON module converts between Ruby objects and JSON strings:

  • Parse: Convert JSON strings into Ruby objects
  • Generate: Convert Ruby objects into JSON strings

Parsing JSON

JSON.parse converts a JSON string into Ruby data structures.

require 'json'

json_string = '{"name": "Alice", "age": 30, "active": true}'
hash = JSON.parse(json_string)

hash["name"]   # => "Alice"
hash["age"]    # => 30
hash["active"] # => true

JSON.parse Parameters

ParameterTypeDefaultDescription
stringStringRequiredThe JSON string to parse
optsHash{}Options for parsing

Parse Options

# Parse arrays
JSON.parse('[1, 2, 3]')  # => [1, 2, 3]

# Parse with symbol keys (Ruby 2.5+)
JSON.parse('{"a": 1}', symbolize_names: true)
# => {:a => 1}

# Allow trailing commas
JSON.parse('{"a": 1,}', allow_nan: true)

Generating JSON

JSON.generate converts Ruby objects into JSON strings.

require 'json'

hash = { name: "Bob", age: 25, tags: ["ruby", "dev"] }
json_string = JSON.generate(hash)
# => "{\"name\":\"Bob\",\"age\":25,\"tags\":[\"ruby\",\"dev\"]}"

You can also use the alias JSON.dump:

JSON.generate({ key: "value" })
JSON.dump({ key: "value" })  # Same thing

JSON.generate Parameters

ParameterTypeDefaultDescription
objectObjectRequiredRuby object to convert
optsHash{}Options for generation

Generate Options

# Pretty-printed output
JSON.pretty_generate({ name: "Carol", items: [1, 2, 3] })
# => {
#      "name": "Carol",
#      "items": [
#        1,
#        2,
#        3
#      ]
#    }

# Use symbols as keys
JSON.generate({ a: 1, b: 2 }, symbolize_names: false)
# => "{\"a\":1,\"b\":2}"

Practical Examples

Working with APIs

require 'json'
require 'net/http'

# Fetch JSON from an API
uri = URI('https://api.example.com/data')
response = Net::HTTP.get(uri)

# Parse the JSON response
data = JSON.parse(response)
puts data["results"]

Configuration Files

require 'json'

# Read config
config = JSON.parse(File.read('config.json'))

# Write config
File.write('config.json', JSON.pretty_generate(config))

Object Serialization

require 'json'

class User
  attr_accessor :name, :email
  
  def initialize(name, email)
    @name = name
    @email = email
  end
  
  def to_json
    { name: @name, email: @email }.to_json
  end
end

user = User.new("Dan", "dan@example.com")
JSON.generate(user)  # => "{\"name\":\"Dan\",\"email\":\"dan@example.com\"}"

See Also