Devlin
Devlin

Reputation: 71

How to parse JSON response in Ruby

The end goal for this is to be part of a chatbot that returns an airport's weather.

Using import.io, I built an endpoint to query the weather service I'd which provides this response:

{"extractorData"=>
  {"url"=>
    "https://www.aviationweather.gov/metar/data?ids=kokb&format=decoded&hours=0&taf=off&layout=on&date=0",
   "resourceId"=>"66ca907842aabb6b08b8bc12049ad533",
   "data"=>
    [{"group"=>
       [{"Timestamp"=>[{"text"=>"Data at: 2135 UTC 12 Dec 2016"}],
         "Airport"=>[{"text"=>"KOKB (Oceanside Muni, CA, US)"}],
         "FullText"=>
          [{"text"=>
             "KOKB 122052Z AUTO 24008KT 10SM CLR 18/13 A3006 RMK AO2 SLP179 T01780133 58021"}],
         "Temperature"=>[{"text"=>"17.8°C ( 64°F)"}],
         "Dewpoint"=>[{"text"=>"13.3°C ( 56°F) [RH = 75%]"}],
         "Pressure"=>
          [{"text"=>
             "30.06 inches Hg (1018.0 mb) [Sea level pressure: 1017.9 mb]"}],
         "Winds"=>
          [{"text"=>"from the WSW (240 degrees) at 9 MPH (8 knots; 4.1 m/s)"}],
         "Visibility"=>[{"text"=>"10 or more sm (16+ km)"}],
         "Ceiling"=>[{"text"=>"at least 12,000 feet AGL"}],
         "Clouds"=>[{"text"=>"sky clear below 12,000 feet AGL"}]}]}]},
 "pageData"=>
  {"resourceId"=>"66ca907842aabb6b08b8bc12049ad533",
   "statusCode"=>200,
   "timestamp"=>1481578559306},
 "url"=>
  "https://www.aviationweather.gov/metar/data?ids=kokb&format=decoded&hours=0&taf=off&layout=on&date=0",
 "runtimeConfigId"=>"2ddb288f-9e57-4b58-a690-1cd409f9edd3",
 "timestamp"=>1481579246454,
 "sequenceNumber"=>-1}

I seem to be running into two issues. How do I:

  1. pull each field and write it into its own variable
  2. ignore the "text" modifier in the response.

Upvotes: 7

Views: 21686

Answers (2)

ithinkiknowruby
ithinkiknowruby

Reputation: 376

If you're getting a response object, you might want to do something like

parsed_json = JSON.parse(response.body)

Then you can do things like parsed_json[:some_field]

Upvotes: 15

the Tin Man
the Tin Man

Reputation: 160551

The simple answer is:

require 'json'

foo = JSON['{"a":1}']
foo # => {"a"=>1}

JSON is smart enough to look at the parameter and, based on whether it's a string or an Array or Hash, parse it or serialize it. In the above case it parsed it back into a Hash.

From that point it takes normal Ruby to dive into the hash you got back and access particular values:

foo = JSON['{"a":1, "b":[{"c":3}]}']
foo # => {"a"=>1, "b"=>[{"c"=>3}]}
foo['b'][0]['c'] # => 3

How to walk through a hash is covered extensively on the internet and here on Stack Overflow, so search around and see what you can find.

Upvotes: 6

Related Questions