It's easy to jump into parsing and generating JSON in Ruby with the json gem. It provides an API for parsing JSON from text as well as generating JSON text from arbitrary Ruby objects. It's easily the most used JSON library in Ruby.
Installing the JSON Gem
On Ruby 1.8.7, you'll need to install a gem. However, in Ruby 1.9.2, the json gem is bundled with the core Ruby distribution. So, if you're using 1.9.2, you're probably all set. If you're on 1.8.7, you'll need to install a gem.
Before you install the JSON gem, first realize that this gem is distributed in two variants. Simply installing this gem with gem install json will install the C extension variant. This requires a C compiler to install, and may not be available or appropriate on all systems. Though if you can install this version, you should.
If you can't install the C extension version, you should gem install json_pure instead. This is the same gem implemented in pure Ruby. It should run everywhere that Ruby code runs, on all platforms and on a variety of interpreters. However, it's considerably slower than the C extension version.
Once installed, there are a few ways to require this gem. A require 'json' (after a prerequisite require 'rubygems' if needed) will require whichever variant is available and will prefer the C extension variant if both are installed. A require 'json/pure' will explicitly require the pure variant, and a require 'json/ext' will explicitly require the C extension variant.
Before we start, let's define some simple JSON to parse. JSON is typically generated by web applications and can be quite daunting, with deep hierarchies that are difficult to navigate. We'll start with something simple. The top level of this document is a hash, the first two keys hold strings and the last two keys hold arrays of strings.
"CEO": "William Hummel",
"CFO": "Carlos Work",
"Research and Development":
So parsing this is quite simple. Assuming this JSON is stored in a file called employees.json, you can parse this into a Ruby object like so.
json = File.read('employees.json')
empls = JSON.parse(json)
And this program's output. Note that if you're running this program on Ruby 1.8.7, the order the keys are retrieved from the hash is not necessarily the same order they're inserted. So your output may appear out of order.
"Inez Rockwell", "Kay Mcginn", "Larry Conn", "Bessie Wolfe",
"Research and Development"=>
"Norman Reece", "Betty Prosser", "Jeffrey Barclay"}
The empls object itself is just a hash. Nothing special about it. It has 4 keys, just as the JSON document had. Two of the keys are strings, and two are arrays of strings. No surprises, the JSON was faithfully transcribed in Ruby objects for your perusal.
And that's about all you need to know about parsing JSON. There are some issues that come up, but those will be covered in a later article. For just about every case, you simply read a JSON document from a file or over HTTP and feed it to JSON.parse.