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
JSON.generateturns a hash into a compact string.JSON.parsereturns string-keyed hashes by default.symbolize_names: truerestores symbol keys on the way back.
Keywords and builtins used here
nameputsrequire
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.
Step 3 of 3 in Files & errors, step 27 of 29 in Language basics.