Question

Hello Im using HTTParty to call for a remote json file that I need to extract the URL's to use in one of my tests.. the json format goes something like:

  "manifest" : {
    "header" : {
      "generated" : "xxxxxxxxxxxxxxx",
      "name" : "xxxxxxxxxxx",
      "version" : "1.0.0"
    },
    "files" : [ {
      "file" : "blimp.zip",
      "url" : "http://www.xxx.xx/restaurants_blimp.zip",
      "checksum" : "ee98c9455b8d7ba6556f53256f95"
    }, {
      "file" : "yard.zip",
      "url" : "www.xxx.xx/yard.zip",
      "checksum" : "e66aa3d123f804f34afc622b5"
    }

on irb I can get all the sub hashes inside example: ['manifest']['files'] and I can only get the url if I expecify which one.. like for example puts file['manifest']['files']['1']['url'] <-- this does work on irb but since I need to get ALL url's this is why I use .each but it gives me a cant convert to string error or similar

#!/usr/bin/env ruby

require 'httparty'

HOST=ARGV[0]
ID=ARGV[1]
VERSION=ARGV[2]


class MyApi
  include HTTParty
end

file = MyApi.get("http://#{HOST}/v1/dc/manifest/#{ID}/#{VERSION}")


file.each do |item|
 puts item['manifest']['files']['url']
end

not working but I can on IRB do a:

puts item['manifest']['files'][2]['url'] <-- and this will give me the url but with the .each will just complaint about cant convert to string or similar

Was it helpful?

Solution

Try the following:

#!/usr/bin/env ruby

require 'httparty'

(HOST, ID, VERSION) = ARGV

class MyApi
  include HTTParty
  format :json
end

response = MyApi.get("http://#{HOST}/v1/dc/manifest/#{ID}/#{VERSION}")

puts response.inspect

The addition of the format :json tells HTTParty to parse the response as JSON. Then you'll get a hash you can iterate over properly.

OTHER TIPS

Try:

file['manifest']['files'].each do |item|
   puts item['url']
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top