Tips and Tricks: JSON in IRB or Pry

Trick one: Parse your raw JSON objects when you pull them in.

For our Ruby Gem project, we were pulling down JSON-formatted data from the Wikipedia  API. To successfully work with JSON in IRB, I imported the object with an HTTP gem and then parsed the JSON data with the JSON gem. EX:

require 'json' 
require 'rest_client' 
JSON.parse(RestClient.get <URL>)

Which gives us a nice Hash output that looks like this:

{"query-continue"=&gt;
    {"images"=&gt;
        {"gimcontinue"=&gt;"736|Citizen-Einstein.jpg"}},
    "query"=&gt;
        {"pages"=&gt;
            {"-1"=&gt;{"ns"=&gt;6, "title"=&gt;"File:1919 eclipse positive.jpg", "missing"=&gt;""},
             "-2"=&gt;{"ns"=&gt;6, "title"=&gt;"File:Albert Einstein's exam of maturity grades (color2).jpg", "missing"=&gt;""}}}}

Without parsing, the information was still in JSON format, a thing that looked like:

"{\"query-continue\":{\"images\":{\"gimcontinue\":\"736|Citizen-Einstein.jpg\"}},\"query\":  ...

with extra quotation marks and all the backslashes, and Ruby got pretty cranky about trying to work with that string.

Trick Two: ‘puts’ your JSON

For another project, I was converting hashes into JSON, and I was getting a bit frustrated. I was quite certain that I was converting the hash into JSON correctly, but I kept getting extraneous backslash-escaped quotation marks in my JSON returns like before.

"{\"query-continue\":{\"images\":{\"gimcontinue\":\"736|Citizen-Einstein.jpg\"}}, ...

Thanks to some StackOverflow googling, I realized/remembered that this was because I was directly calling the JSON in the console, instead of puts-ing it from within the script I was running. When I used a puts statement inside the script, I could see that my output was actually formatted correctly, as I expected. Using puts in the console also worked to show me the JSON with it’s correct formatting.

puts <JSON>

instead of

<JSON>

One thought on “Tips and Tricks: JSON in IRB or Pry

  1. Pingback: Tips and Tricks: JSON in IRB – MakerSquare Blog

Leave a Reply

Your email address will not be published. Required fields are marked *