JSON and YAML

Contents
JSON stdlib
Parse JSON
Generate JSON
YAML with psych

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: HTTP clients

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: