pythonjsonrubydashing

Parsing JSON feed with Ruby for use in Dashing Dashboard


First post here, so ya know, be nice?

I'm setting up a dashboard in Dashing (http://dashing.io/) using a JSON feed on a server, which looks like:

{  
   "error":0,
   "message_of_the_day":"Welcome!",
   "message_of_the_day_hash":"a1234567890123456789012345678901",
   "metrics":{  
      "daily":{  
         "metric1":"1m 30s",
         "metric2":160
      },
      "monthly":{  
         "metric1":"10m 30s",
         "metric2":"3803"
      }
   },

I have been experimenting with grabbing the data from the feed, and have managed to do so by Python with no issues:

import json
import urllib2

data = {
        'region': "Europe"
}

req = urllib2.Request('http://192.168.1.2/info/handlers/handler.php')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

print response.read()

However I haven't yet been successful, and get numerous errors in Ruby. Would anyone be able to point me in the right direction in parsing this in Ruby? My attempts to write a basic script, (keeping it simple and outside of Dashing) don't pull through any data.

#!/usr/bin/ruby
require 'httparty'
require 'json'

response = HTTParty.get("http://192.168.1.2/info/handlers/handler.php?region=Europe") 

json = JSON.parse(response.body)

puts json

Solution

  • In python code you are sending a JSON and adding a header. I bet it makes sense to do that in ruby as well. The code below is untested, since I can’t test it, but it should lead you into the right direction:

    #!/usr/bin/ruby
    require 'httparty'
    require 'json'
    
    response = HTTParty.post(
      "http://192.168.1.2/info/handlers/handler.php",
      headers: {'Content-Type', 'application/json'},
      query: { data: { 'region' => "Europe" } } 
      # or maybe query: { 'region' => "Europe" }
    ) 
    
    puts response.inspect