Ruby JSON Library
Working with JSON data in Ruby
📄 What is the JSON Library?
Ruby's JSON library provides methods to parse JSON strings into Ruby objects and convert Ruby data structures into JSON format. Essential for API communication, data storage, and exchanging information between different systems and programming languages.
require 'json'
# Parse JSON to Ruby
data = JSON.parse('{"name": "Ruby", "version": 3.2}')
puts data['name'] # => Ruby
Output:
Ruby
Key JSON Operations
Parse
Convert JSON to Ruby objects
JSON.parse(string)
Generate
Convert Ruby to JSON
JSON.generate(obj)
Pretty Print
Format JSON with indentation
JSON.pretty_generate
File I/O
Read and write JSON files
JSON.load(file)
🔹 Parsing JSON
Use JSON.parse to convert JSON strings into Ruby hashes and arrays. This is essential when receiving JSON data from APIs, reading configuration files, or processing JSON responses from web services.
require 'json'
# Parse simple JSON
json_string = '{"name": "Alice", "age": 30}'
person = JSON.parse(json_string)
puts person['name'] # => Alice
puts person['age'] # => 30
# Parse JSON array
json_array = '[1, 2, 3, 4, 5]'
numbers = JSON.parse(json_array)
puts numbers[0] # => 1
# Parse nested JSON
nested = '{"user": {"name": "Bob", "email": "[email protected]"}}'
data = JSON.parse(nested)
puts data['user']['name'] # => Bob
puts data['user']['email'] # => [email protected]
Output:
Alice
30
1
Bob
[email protected]
🔹 Generating JSON
Convert Ruby objects into JSON format using JSON.generate or the shorthand .to_json method. This is useful when sending data to APIs, saving configuration, or creating JSON responses in web applications.
require 'json'
# Convert hash to JSON
person = { name: 'Charlie', age: 28, city: 'NYC' }
json = JSON.generate(person)
puts json
# => {"name":"Charlie","age":28,"city":"NYC"}
# Using to_json method
json2 = person.to_json
puts json2
# Convert array to JSON
colors = ['red', 'green', 'blue']
json_array = JSON.generate(colors)
puts json_array
# => ["red","green","blue"]
# Nested structures
data = {
users: [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
]
}
puts JSON.generate(data)
Output:
{"name":"Charlie","age":28,"city":"NYC"}
["red","green","blue"]
🔹 Pretty Printing JSON
Use JSON.pretty_generate to create formatted JSON with proper indentation and line breaks. This makes JSON more readable for humans, perfect for debugging, logging, or creating configuration files.
require 'json'
person = {
name: 'Diana',
age: 32,
address: {
street: '123 Main St',
city: 'Boston',
zip: '02101'
},
hobbies: ['reading', 'coding', 'hiking']
}
# Pretty print with indentation
pretty_json = JSON.pretty_generate(person)
puts pretty_json
# Output:
# {
# "name": "Diana",
# "age": 32,
# "address": {
# "street": "123 Main St",
# "city": "Boston",
# "zip": "02101"
# },
# "hobbies": [
# "reading",
# "coding",
# "hiking"
# ]
# }
Output:
{ "name": "Diana", "age": 32, "address": { "street": "123 Main St" } }
🔹 Reading JSON Files
Load JSON data from files using File.read combined with JSON.parse, or use JSON.load for a shortcut. This is useful for reading configuration files, loading data sets, or importing saved application state.
require 'json'
# Method 1: Read and parse
json_content = File.read('config.json')
config = JSON.parse(json_content)
puts config['database']
# Method 2: Using JSON.load (deprecated in newer versions)
# Use JSON.parse(File.read()) instead
File.open('data.json', 'r') do |file|
data = JSON.parse(file.read)
puts data['title']
end
# Example config.json content:
# {
# "database": "postgresql",
# "host": "localhost",
# "port": 5432
# }
Output:
postgresql
My Application
🔹 Writing JSON Files
Save Ruby objects as JSON files using File.write with JSON.generate. This is perfect for saving application state, creating configuration files, or exporting data in a portable format.
Common Use Cases:
- Configuration - Save app settings
- Data Export - Export data for other apps
- Caching - Store temporary data
- State Management - Save application state
require 'json'
# Create data
users = [
{ id: 1, name: 'Alice', email: '[email protected]' },
{ id: 2, name: 'Bob', email: '[email protected]' },
{ id: 3, name: 'Charlie', email: '[email protected]' }
]
# Write to file
File.write('users.json', JSON.pretty_generate(users))
# Write with File.open
File.open('config.json', 'w') do |file|
config = { app_name: 'MyApp', version: '1.0.0' }
file.write(JSON.pretty_generate(config))
end
puts "Files created successfully!"
Output:
Files created successfully!
🔹 Handling JSON Errors
Always handle potential JSON parsing errors using begin-rescue blocks. Invalid JSON will raise JSON::ParserError, which you should catch to prevent your application from crashing on malformed data.
require 'json'
# Invalid JSON string
invalid_json = '{"name": "Alice", age: 30}' # Missing quotes
begin
data = JSON.parse(invalid_json)
puts data['name']
rescue JSON::ParserError => e
puts "Error parsing JSON: #{e.message}"
end
# Safe parsing with validation
def safe_parse(json_string)
JSON.parse(json_string)
rescue JSON::ParserError
puts "Invalid JSON format"
nil
end
result = safe_parse('{"valid": true}')
puts result['valid'] if result # => true
result = safe_parse('{invalid}')
# => Invalid JSON format
Output:
Error parsing JSON: unexpected token at '...'
true
Invalid JSON format
🔹 Working with Symbols
By default, JSON.parse creates hashes with string keys. Use the symbolize_names option to convert keys to symbols, which is often more convenient when working with Ruby code and accessing hash values.
require 'json'
json_string = '{"name": "Eve", "age": 27, "city": "Seattle"}'
# Default: string keys
data1 = JSON.parse(json_string)
puts data1['name'] # => Eve
# With symbol keys
data2 = JSON.parse(json_string, symbolize_names: true)
puts data2[:name] # => Eve
puts data2[:age] # => 27
puts data2[:city] # => Seattle
# Easier to work with in Ruby
person = JSON.parse(json_string, symbolize_names: true)
puts "#{person[:name]} is #{person[:age]} years old"
Output:
Eve
Eve
27
Seattle
Eve is 27 years old