Working with JSON in Ruby


Here’s how to work with JSON in Ruby.

To parse JSON to Ruby objects

We can use JSON.parse() method as follow:

#JSON Parsing example
require "rubygems"
require "json"
string = '{"desc":{"someKey": "someValue", "anotherKey": "value" } ,"main_item": {"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash
p parsed["desc"]["someKey"]

To dumps/generate JSON from Ruby object

we can use JSON.generate() method as follow:

require 'json' 
my_hash = {:hello => "goodbye"} 
puts JSON.generate(my_hash) 
# ouput will be "{\"hello\":\"goodbye\"}" 

Our Awesome Tools