Extract data from JSON with Ruby

Chef uses Ruby as the scripting language. If you need to extract data out from a JSON string you can use the following script


# Save the JSON values
instance_data_drive_config = '{"size":"500","type":"io1","iops":"15000"}'

# Parse the JSON to a hash
data = JSON.parse(instance_data_drive_config)

# Declare the variables
size = ''
type = ''
iops = ''

# Iterate through the hash
data.each do |child|
case child[0]
when 'size'
size = child[1]
when 'type'
type = child[1]
when 'iops'
iops = child[1]
end
end

# Display the result
puts "size=#{size}"
puts "type=#{type}"
puts "iops=#{iops}"

The output is
size=500
type=io1
iops=15000

Leave a Reply