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 # HashParse 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] # AliceGenerate 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']Related Tools
Frequently Asked Questions
How do I parse JSON in Ruby?▾
Require 'json' and call JSON.parse(json_string). It returns a Hash with string keys. Pass symbolize_names: true to use symbol keys instead.
How do I generate JSON in Ruby?▾
Call .to_json on any Hash, Array, String, Integer, Float, true, false, or nil. For pretty output use JSON.pretty_generate(data).
How do I read a JSON file in Ruby?▾
Use JSON.parse(File.read('file.json')). Add symbolize_names: true if you prefer symbol keys. For large files, use the json gem's streaming API.
How do I handle JSON parse errors in Ruby?▾
JSON.parse raises JSON::ParserError on invalid input. Rescue it: begin; JSON.parse(str); rescue JSON::ParserError => e; puts e.message; end.
What is the difference between JSON.parse and JSON.load in Ruby?▾
JSON.load is designed for trusted data only — it can deserialize arbitrary Ruby objects and is unsafe with user input. Always use JSON.parse for untrusted JSON strings.
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.