From: jason joo Date: 2010-08-12T14:02:32+09:00 Subject: Re: does jason convert to hash? --000e0cd3317e89a6cc048d9945dc Content-Type: text/plain; charset=ISO-8859-1 in ur example data there are only 3 items in the "result" and the element of "count" has a value of 52 in ur for-loop u will access 3-51 ones which do not exist u may use table["results"].size instead of table["count"] 2010/8/12 Samuel Sternhagen > I am trying to work with the Etsy API. I make a HTTP request and get > data back in json format. I call JSON.parse(table) and the parse method > returns the data in something that appears to be a hash. > > Here is a simplified version of what JSON.parse(table) returns: > > {"results"=>[{"name"=>"getMethodTable", "uri"=>"/", > "http_method"=>"GET", "type"=>"method", "defaults"=>nil, "params"=>nil, > "description"=>"Get a list of all methods available.", > "visibility"=>"public"}, {"name"=>"getSubCategory", > "uri"=>"/categories/:tag/:subtag", "http_method"=>"GET", > "type"=>"Category", "defaults"=>nil, "params"=>{"subtag"=>"string", > "tag"=>"string"}, "description"=>"Retrieves a second-level Category by > tag and subtag.", "visibility"=>"public"}, {"name"=>"getSubSubCategory", > "uri"=>"/categories/:tag/:subtag/:subsubtag", "http_method"=>"GET", > "type"=>"Category", "defaults"=>nil, "params"=>{"subtag"=>"string", > "tag"=>"string", "subsubtag"=>"string"}, "description"=>"Retrieves a > third-level Category by tag, subtag and subsubtag.", > "visibility"=>"public"}], "type"=>"method", "count"=>52, "params"=>nil} > > I am trying to access each of these hashes and each of the sub hashes. I > do not think that I am using the correct syntax. > > I can get some of the values by refering to: > > table["results"][i] # then iterate through i > > This is the code I use to access the key value pairs. > > require 'rubygems' > require 'json' > require 'net/http' > > class MethodTable # returns hash containing results from Etsy's API > method: getMethodTable > def get_table > url = "http://openapi.etsy.com/v2/sandbox/public/?api_key=my_key" > url = URI.parse(url) > method_list = Net::HTTP.get(url) > end > end > > method_table = MethodTable.new > table = method_table.get_table > table = JSON.parse(table) > > i = 1 > > while (i <= table["count"]) > > table["results"][i].each do |key, value| > print "#{key} => #{value}\n" > end > i += 1 > end > > table.rb:21: undefined method `each' for nil:NilClass (NoMethodError) > > How can I use `each' without and error? How can I access the sub-hashes > such as the hash of parameters seen below? > > "params"=>{"subtag"=>"string", "tag"=>"string", "subsubtag"=>"string"} > > > Thanks, > > Sam > -- > Posted via http://www.ruby-forum.com/. > > --000e0cd3317e89a6cc048d9945dc--