jsondecode.com logo

JSON in Ruby — Parse, Generate & Work with Hashes

Ruby's standard library includes the json gem. Require 'json' to access JSON.parse() and .to_json.

Parse a JSON string

JSON.parse() returns a Hash with string keys by default.

require 'json'

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

puts data['name']   # Alice
puts data['age']    # 30
puts data.class     # Hash

Parse with symbol keys

Pass symbolize_names: true to use symbols instead of strings as hash keys.

data = JSON.parse(json_string, symbolize_names: true)

puts data[:name]  # Alice

Generate JSON

Call .to_json on any Hash, Array, String, Integer, Float, true, false, or nil.

data = { name: 'Alice', scores: [95, 87], active: true }
puts data.to_json
# {"name":"Alice","scores":[95,87],"active":true}

# Pretty-print
puts JSON.pretty_generate(data)

Read a JSON file

Read the file contents and parse with JSON.parse().

require 'json'

data = JSON.parse(File.read('data.json'))
puts data['name']

Format and validate your JSON instantly

Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.

Open JSON Formatter →