Convert a Ruby Hash into valid JSON

This post is about how to get a valid JSON (JavaScript Object Notation) snippet from a Ruby Hash.

In the world of Ruby, Ruby loves hashes. It’s great because it allows you to access values with keys. With require 'json', you can easily parse a JSON formatted string into a Ruby hash with JSON.parse(json_string). You can easily tell hashes by their hash rockets (=>) and JSON by its usage of colons (:).

require 'json'
animal_count = {"tiger"=>3, "lion"=>2, "dog"=>2, "cat"=>3, "mouse"=>1, "bear"=>1, "frog"=>2, "fish"=>1}
animal_count.class #=> Hash
animal_count.methods #=> :to_json

By using require 'json', you get access to the to_json method on hashes. Unfortunately, they look like this:

json_animals = animal_count.to_json #=> "{\"tiger\":3, \"lion\":2, \"dog\":2, \"cat\":3, \"mouse\":1, \"bear\":1, \"frog\":2, \"fish\":1}"
json_animals.class #=> String

If you paste the string "{\"tiger\":3,\"lion\":2,\"dog\":2,\"cat\":3,
\"mouse\":1,\"bear\":1,\"frog\":2,\"fish\":1}" into JSON Lint, you’ll find that it’s invalid JSON due to a Parse Error.

The backslash character (\) is there to escape the quotes for serialization (Ruby object to transportable string) and deserialization (string to Ruby object).

The good news is that the solution in IRB is extremely easy.

puts json_animals #=> {"tiger":3,"lion":2,"dog":2,"cat":3,"mouse":1,"bear":1,"frog":2,"fish":1}

With puts, the new return String passes JSON Lint as Valid JSON.

Using puts may seem obvious, but it’s the seemingly small things like this that make all the difference in the world. One is properly escaped but invalid, while the other is valid, usable JSON.

(Thanks to Avi for helping me with this @Flatironschool)

One thought on “Convert a Ruby Hash into valid JSON