JSON parsing with ruby one-liner ?

Parsing JSON is one of the most common tasks that any web developer does in his daily activities.

Parsing JSON with ruby with is fun and the fun multiples n.times when the code is a one-liner

Indeed some gems are needed along with ruby and rubygems, you shall need :

gem install rest-client

With all the above gems, begins the fun! Say you have a simple json that gives the IP of your machine unlike http://h3manth.com/ip.php which was specifically designed for jsonp!

So say the json string is like {ip:}

Using the simple ruby one-liner below, this is what happens with that json:

require 'rubygems'
require 'json'
require 'rest-client' 
json_ip_url = "http://ifconfig.me/all.json"
# The killer one line ruby json parsing! 
ip_details = JSON.parse(RestClient.get(json_ip_url))

The json from the URL looks like :

    "connection": "keep-alive",
    "ip_addr": "",
    "lang": "en-US,en;q=0.8",
    "remote_host": "NSG-Static-",
    "user_agent": "Mozilla/5.0",
    "charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "port": "4532",
    "via": "",
    "forwarded": "",
    "keep_alive": "",
    "encoding": "gzip,deflate,sdch"

And the killer ruby one line JSON parser  Crack::JSON.parse(RestClient.get(json_ip_url)) returns a wonderful hash like :

    "connection" = > "", 
    "ip_addr" = > "",
    "lang" = > "", 
    "remote_host" = > "NSG-Static-", 
    "user_agent" = > "Ruby", 
    "charset" = > "", 
    "port" = > "24436", 
    "via" = > "", 
    "forwarded" = > "", 
    "mime" = > "* / *; q=0.5, application/xml", 
    "keep_alive" = > "", 
    "encoding" = > "gzip, deflate"

With that, one can just use ip_details["json_key"] to get the required details!

Let's try something more, one liners are always fun and when it's ruby and the web, it's more fun!

Let's get the top three images from Google image search!

#!/usr/bin/env ruby 
require 'rubygems'
require 'json'
require 'rest-client' 
require 'uri'
def get_imgs(term)
  imgs = JSON.parse(RestClient.get(url))
  for img in imgs["responseData"]["results"]
      puts img["url"]
get_imgs("yoda") would print

So far this has been my best way of parsing JSON with ruby, what's yours?

Edit : Define one-liner? :D It must have been JSON parsing in a line, right?

Share this