Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Which way is better to handle JSON with Crystal

Which way is better to handle JSON with Crystal

Takuya Arita

August 01, 2015
Tweet

More Decks by Takuya Arita

Other Decks in Programming

Transcript

  1. The legacy way require "http/client" require "json" place = ARGV[0]

    url = "http://api.openweathermap.org/data/2.5/weather?q=#{place}" resp = HTTP::Client.get(url) weather = JSON.parse(resp.body) pp (((weather as Hash)["weather"] as Array)[0] as Hash)["main"] puts "-" * 80 pp weather
  2. Crystal way require "http/client" require "json" class WeatherResponse json_mapping({ weather:

    Array(Weather), }) class Weather json_mapping({ id: Int32, main: String, description: String, icon: String, }) end end place = ARGV[0] url = "http://api.openweathermap.org/data/2.5/weather?q=#{place}" resp = HTTP::Client.get(url) puts "-" * 80 weather_resp = WeatherResponse.from_json(resp.body) pp weather_resp pp weather_resp.weather[0].main
  3. end