maclover7
maclover7

Reputation: 137

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

{ 
  "daily": {
    "summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.",
    "icon":"rain",
    "data":[
      {
        "time":1435464000,
        "precipProbability":0.99
      }
    ]
  }
}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time when it is 1435464000. Any suggestion on how to complete my current JSON parsing query?

Upvotes: 1

Views: 143

Answers (4)

Aman srivastava
Aman srivastava

Reputation: 1

require 'Faraday'
require "JSON"

connection = Faraday.new(JSON.file)
response = connection.get

data_hash = JSON.parse(response.body)["daily"]
data_hash.each do |item|
p item

end

Upvotes: 0

Ojash
Ojash

Reputation: 1234

The easiest solution to your query would be

forecast["daily"]["data"].first['precipProbability']

However I suggest you make it inside a loop as there might be no data or more than one data on the array

forecast["daily"]["data"].each do |data|
  puts data['precipProbability'] # or your implementation logic 
end

Upvotes: 1

ABMagil
ABMagil

Reputation: 5675

Anytime you're looking through an iterable like an array, it's nice to use the methods in the Enumerable module

In this case, your data is an array, and you're looking for objects which match a condition (time = 1435464000), so you're looking for the detect method, also known by the more descriptive name find.

data_on_day_you_want = forecast["daily"]["data"].detect{ |h| h["time"] == 1435464000 }
precip = data_on_day_you_want["precipProbability"]

Obviously this can be inlined or broken apart into more methods, but the important thing is the detect. You pass it a block, and it returns the first element of the data array which returns true for that block.

Upvotes: 1

Leo Correa
Leo Correa

Reputation: 19839

Since the data field is an array of objects you can access each of it's member's properties like you would any Enumerable.

If you want to find the data for the time 1435464000 simply do the following with Enumerable#find

data = forecast["daily"]["data"].find { |d| d["time"] == 1435464000 }
# ensure data exists for time
if data
  data["precipProbability"]
end

Upvotes: 2

Related Questions