Convert a Ruby Hash into valid JSON

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

The following is a guest post by Rex Feng and originally appeared on his blog. Rex is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

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 (:).

Blog post image: tumblr_inline_mgbls6B92i1rtan47.png

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

Blog post image: tumblr_inline_mgblrp8BUO1rtan47.png

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.

Blog post image: tumblr_inline_mgblrdPQ8S1rtan47.png

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.

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat