3

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
  • 1
    There is a closing '}' missing in the JSON you have posted. – ReggieB Sep 23 '16 at 11:11
  • I think if the Content-Type is application/json, then HTTParty will parse it for you. What is the error? What does `puts response` show? – B Seven Sep 23 '16 at 17:45

1 Answers1

2

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
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • If @mudasobwa is right - and I think they may well be - you should be able to work out what is going on by printing out the response body `puts response.body` it should print out the json. If it prints out an HTML page, the lack of content type in the request is the problem. – ReggieB Sep 23 '16 at 11:15