JSON and YAML

JSON stdlib

The json library converts between Ruby objects and JSON text. Require it once at the top of the file.

Hashes become JSON objects, arrays stay arrays, and symbols turn into quoted names. Dates travel as strings inside such payloads, formatted as in Time and date.

require "json"

Parse JSON

parse reads a JSON string into hashes and arrays. Keys arrive as strings, so fetch them with string keys.

Symbol access needs an extra option, which beginners can skip until the shape of data feels familiar.

require "json" data = JSON.parse("{\"name\": \"Ada\"}") puts data["name"]

Generate JSON

generate turns hashes and arrays back into text. Build the structure from plain Ruby objects and let the library handle quoting.

Pretty output with extra spaces exists for config files humans read, while compact output suits network traffic.

require "json" user = { name: "Ada", age: 36 } puts JSON.generate(user)

YAML with psych

Psych is the YAML engine behind the yaml library. dump writes objects as readable YAML, and safe_load reads trusted data back.

Prefer safe_load over load for outside text: it blocks surprise object creation from hostile files.

require "yaml" data = YAML.safe_load("name: Ada") puts data["name"]

Next: CSV

Article author: Arthur Isaev