iterate through json variables in ruby

To iterate through JSON variables in Ruby, you need to first parse the JSON data into a Ruby object using the JSON.parse() method. Once you have the parsed object, you can iterate over it using various Ruby methods such as each, each_pair, or each_with_index.

Here's an example of iterating through a JSON object using the each_pair method:

main.rb
require 'json'

json_data = '{"name": "John Smith", "age": 35, "city": "New York"}'

ruby_data = JSON.parse(json_data)

ruby_data.each_pair do |key, value|
  puts "#{key}: #{value}"
end
186 chars
10 lines

This will output:

main.rb
name: John Smith
age: 35
city: New York
40 chars
4 lines

You can also iterate over JSON arrays using the each method:

main.rb
require 'json'

json_data = '[{"name": "John Smith", "age": 35}, {"name": "Jane Doe", "age": 28}]'

ruby_data = JSON.parse(json_data)

ruby_data.each_with_index do |person, index|
  puts "Person ##{index + 1}: #{person['name']} is #{person['age']} years old"
end
263 chars
10 lines

This will output:

main.rb
Person #1: John Smith is 35 years old
Person #2: Jane Doe is 28 years old
74 chars
3 lines

gistlibby LogSnag