Convert a Ruby Hash into valid JSON
Reading Time 1 min
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', you get access to the
to_json method on hashes. Unfortunately, they look like this:
If you paste the string
“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, the new return String passes JSON Lint as Valid JSON.
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.
Interested in starting a career in coding? Our full-time software engineering bootcamp teaches students the skills they need to become professional software engineers in as little as 15 weeks.
We also offern our online software engineering bootcamp for students who need a bit more flexibility, or simply just want to learn from the comfort of their own home.
Posted by Flatiron School / January 9, 2013
Learn to Code Python: Free Lesson for Beginners
What is the difference between a data analyst and a data scientist?
While data analyst and data scientist roles attract similar types of creative and logical people, their roles do have stark differences. Here’s our breakdown of the lines between these often mixed up roles.