JSON APIs
Returning JSON.
Why JSON APIs?
JSON is the standard data format for web APIs. Clients send and receive structured data instead of HTML.
- Language independent
- Maps cleanly to Ruby hashes and arrays
- Lightweight and human readable
Ruby's standard library handles JSON via the json module.
require 'json'
data = { name: 'Ada', langs: ['Ruby', 'Python'] }
puts data.to_jsonConverting Ruby to JSON
Call to_json on a hash or array, or use JSON.generate.
- Symbols and strings become JSON keys
- Nested structures convert recursively
require 'json'
user = { id: 1, active: true, tags: ['admin'] }
puts JSON.generate(user)