-1

I'm working on a Ruby code that receive a json file (from Flurry API) and create another json friendly-format for "Status Board" app. When using this json fragment:

"country":[{"@country":"US","day":[{"@date":"2013-09-20","@value":"1"},
{"@date":"2013-09-   23","@value":"1"}]},
{"@country":"KR","day":{"@date":"2013-09-20","@value":"1"}}

Everything works fine, but when the code read "KR" and then "day" (note the lack of "[]") I receive the following error:

  • `[]': can't convert String into Integer (TypeError)

The code I use to read the original json file is:

countries = response.parsed_response["country"]
   countries.each do |datapoint|
      countryName = datapoint["@country"]
      days = datapoint["day"]
      data = []
      days.each do |datapoint2|
          value = datapoint2["@value"]
          date = Date.parse(datapoint2["@date"])
          dateString = date.strftime(dateFormat)
          data << { :title => dateString, :value => value }
      end
      dataSequences << { :title => countryName, :color => metric[:color], :datapoints => data 
   }
   end

I'm kind of noob in Ruby, so...It is possible to add brackets when reading a json file to avoid this error?

Jesod
  • 51
  • 7
  • Which line is pointed by your error? EDIT: You probably pass `String` instance to `Array#[]` method somewhere. – Marek Lipka Sep 24 '13 at 07:24
  • The error shows right after: "days.each do |datapoint2|". It fails reading "@value" or "@date" (I'm tried both). When I print datapoint2 it shows: {"@date":"2013-09-20","@value":"1"} -> Without brackets. – Jesod Sep 24 '13 at 19:44

1 Answers1

0

Ruby includes a few type coercion methods that you might find useful.

The first is Array(), which will convert its argument into an array, unless the argument is already one, it which case it simply returns the argument:

Array(1) #=> [1]
Array([1,2,3]) #=> [1,2,3]

Somewhat annoyingly, when fed a single hash, it converts the hash into an array of arrays (the key-value pairs in the hash):

Array({ a: 1, b: 2}) #=> [[:a, 1], [:b, 2]]

However, there is also a Hash[] method that will convert that result back into a hash, but leave existing hashes alone:

Hash[ [[:a, 1], [:b, 2]] ] #=> { a: 1, b: 2 }

Since your 'day' key is sometimes an array of hashes and sometimes a single hash, you can use these in your method to ensure your iterations and lookups work as expected:

Array(datapoint["day"]).each do |datapoint2|
  dp2_hash = Hash[datapoint2]
  # ... etc, substituting future mentions of datapoint2 with dp2_hash
Zach Kemp
  • 11,736
  • 1
  • 32
  • 46