Ruby JSON.parse
JSON.parse turns an object into a hash with string keys by default. Hash#fetch can supply a result for a missing member.
A simple example
JSON.parse
- Start with JSON text {"n":2}
- Do this Decode and read field n
- Result Number 2
Syntax
record = JSON.parse(text)
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Separate a missing value from a JSON syntax error
A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.
require 'json'
['{"qty":0}', '{}', '{"qty":}'].each do |text|
begin
puts JSON.parse(text).fetch('qty', 'unspecified')
rescue JSON::ParserError
puts 'invalid JSON'
end
end
0 unspecified invalid JSON
An absent quantity can use the fallback while the numeric value zero is preserved. Malformed JSON raises JSON::ParserError during parsing.
Ruby documentation for JSON.parse
Read a locker report
A locker controller sends the number of free doors as JSON. Decode the JSON record before reading its count field. Which numeric count reaches the desk?
Record an empty tray
A sorter sends an explicit count of zero for an empty tray. Decode the JSON record before reading its count field. Which numeric count reaches the desk?