JSON with Ruby
JSON is a popular format for
exchanging information between systems.
🖥️ ↔️ 📄 ↔️ 🖥️
That's mainly because it's easy to read and write for
humans 👩🦱 and machines 🤖.
Many programming languages have built-in support for
reading and writing JSON documents
... so does Ruby.
require 'json'
JSON.parseconverts a Ruby-String containing JSON into a Ruby object.
JSON.generateconverts a Ruby object into a Ruby-String containing JSON.
JSON.parsewe can read a JSON object and convert it into a Hash or Array.
require 'json'
movie_as_json = '{
"title": "Shrek",
"rating": 90,
"filmingLocation": null
}'
movie = JSON.parse(movie_as_json)
puts movie
# => {"title"=>"Shrek", "rating"=>90, "filmingLocation"=>nil}
Note that the key "filmingLocation" has not been changed to snake_case, but that's OK.
JSON.generatewe can generate a JSON object from any Hash or Array.
require 'json'
actress = {
name: "Emma Watson",
academy_awards: nil
}
actress_as_json = JSON.generate(actress)
puts actress_as_json
# => {"name": "Emma Watson", "academy_awards": null}
Note that the key "academy_awards" has not been changed to camelCase either.
Why would we do all of this "generate-parse"-cycle?
Within our own application it does not make much sense to use JSON.
But if our application wants to "talk" to another application (that may not be built in Ruby), we often use JSON for communication.
That other application we call an
Or do you know any services that you think they could be APIs?
Let's see how this could work
require 'json'
request = { location: "Edinburgh" }
request_as_json = JSON.generate(request)
# => "{\"location\":\"Edinburgh\"}"
answer_from_server = WeatherServer.send(request_as_json)
# => "{\"tempC\": 14, \"conditions\": \"Heavy Rain\"}"
forecast = JSON.parse(answer_from_server)
# => {"tempC"=>14, "conditions"=>"Heavy Rain"}
WeatherServeris implemented, since it's not in our focus here.
What questions do you have?