typestar

JSON in Ruby

Serializing to JSON and back with the standard library.

require "json"

payload = { name: "typestar", langs: ["ruby", "go"], stars: 3 }
text = JSON.generate(payload)
puts text

parsed = JSON.parse(text)
puts parsed["name"]
puts parsed["langs"].length

puts JSON.pretty_generate(stars: parsed["stars"])

# symbolize_names gets symbol keys back after the round trip
round = JSON.parse(text, symbolize_names: true)
puts round[:stars]

How it works

  1. JSON.generate turns a hash into a compact string.
  2. JSON.parse returns string-keyed hashes by default.
  3. symbolize_names: true restores symbol keys on the way back.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
374
Tokens
95
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 3 of 3 in Files & errors, step 27 of 29 in Language basics.

← Previous Next →

JSON in other languages