Ruby on Rails Parsing JSON

Ruby on Rails Parsing JSON

Sometime you have to deal with parsing out JSON. Luckily, this is very easy in any recent version of Ruby. Given the string below:

1
2
3
4
5
6
{
  "products": [{
    "name": "Mac Pro",
    "price": "2500"
  }]
}

You can easily parse this string by using:

1
2
require 'json'
h = JSON.parse(string)

In the above code, it will return a ruby hash that mimics the JSON structure. This means that you can do stuff like this:

1
h["products"][0]["name"] # => "Mac Pro"

So far so good, that’s it! See ya! :)