In the realm of programming, handling JSON (JavaScript Object Notation) is a fundamental skill, especially in web development. Ruby, with its elegant syntax, provides straightforward methods for parsing and generating JSON data. This guide presents three diverse and practical examples of Ruby JSON handling to illustrate how you can effectively work with JSON.
When you receive JSON data as a string (e.g., from an API response), you need to convert it into a Ruby hash to manipulate it easily.
require 'json'
json_string = '{"name": "John", "age": 30, "city": "New York"}'
parsed_data = JSON.parse(json_string)
puts "Name: #{parsed_data['name']}"
puts "Age: #{parsed_data['age']}"
puts "City: #{parsed_data['city']}"
This example showcases how to convert a JSON string into a Ruby hash. The JSON.parse
method is used to perform the conversion, allowing you to access the data using standard hash syntax.
JSON::ParserError
will occur.In scenarios where you need to send data as JSON (e.g., in web applications), you can easily convert Ruby objects to JSON format.
require 'json'
ruby_hash = { name: 'Alice', age: 28, city: 'Los Angeles' }
json_data = JSON.generate(ruby_hash)
puts json_data
In this example, we use JSON.generate
to convert a Ruby hash into a JSON string. This is essential when you need to send data to a client or store it in a JSON database.
JSON.generate
, such as pretty printing.When dealing with a collection of objects, you may receive or need to generate a JSON array. This example highlights how to work with arrays in JSON.
require 'json'
ruby_array = [
{ 'name' => 'Bob', 'age' => 35, 'city' => 'Chicago' },
{ 'name' => 'Carol', 'age' => 32, 'city' => 'Miami' }
]
json_array = ruby_array.to_json
puts json_array
parsed_array = JSON.parse(json_array)
parsed_array.each do |item|
puts "Name: #{item['name']}, Age: #{item['age']}, City: #{item['city']}"
end
This example demonstrates how to create a JSON array from a Ruby array of hashes using to_json
. We then parse the JSON back into a Ruby structure and iterate through it.
json
library required in your script.These examples of Ruby JSON handling examples provide a foundational understanding of how to work with JSON in Ruby. By mastering these techniques, you can efficiently manipulate and transmit data in your applications.