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:
3 | JSON .parse(RestClient.get < URL >) |
Which gives us a nice Hash output that looks like this:
3 | { "gimcontinue" => "736|Citizen-Einstein.jpg" }}, |
6 | { "-1" =>{ "ns" =>6, "title" => "File:1919 eclipse positive.jpg" , "missing" => "" }, |
7 | "-2" =>{ "ns" =>6, "title" => "File:Albert Einstein's exam of maturity grades (color2).jpg" , "missing" => "" }}}} |
Without parsing, the information was still in JSON format, a thing that looked like:
1 | "{\"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.
1 | "{\"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.
instead of