Library contents

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

  1. Start with JSON text {"n":2}
  2. Do this Decode and read field n
  3. Result Number 2
Decoding turns the text representation into an object or record with a numeric field.

Syntax

Ruby 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.

First output line0
lesson.rb
require 'json'

['{"qty":0}', '{}', '{"qty":}'].each do |text|
  begin
    puts JSON.parse(text).fetch('qty', 'unspecified')
  rescue JSON::ParserError
    puts 'invalid JSON'
  end
end
Output
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

Advertisements

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?

Given{"count":4}
Worked result4

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?

Given{"count":0}
Worked result0