Class: BEL::JSON::Implementation

Inherits:
Object
  • Object
show all
Includes:
Reader, Writer
Defined in:
lib/bel/json/adapter/oj.rb,
lib/bel/json/adapter/ruby_json.rb,
lib/bel/json/adapter/multi_json.rb

Overview

Implementation of JSON reading/writing using stream-based approaches in Oj.

Instance Method Summary collapse

Instance Method Details

#read(data, options = {}) { ... } ⇒ Enumerator

Reads JSON from an IO using a streaming mechanism in Oj. Yields to the block, or returns Enumerator, of Hash (JSON objects) and Array (JSON arrays).

Parameters:

  • data (IO)

    an IO-like object

  • options (Hash) (defaults to: {})

    supplemental options to Oj; default is to set the :symbol_keys option to true

Yields:

  • each completed Hash (JSON object) or completed Array (JSON array)

Returns:

  • (Enumerator)

    contains an enumeration of Hash (JSON object) and Array (JSON array)



24
25
26
27
28
29
30
31
# File 'lib/bel/json/adapter/oj.rb', line 24

def read(data, options = {}, &block)
  if block_given?
    options = { :symbol_keys => true }.merge!(options)
    Oj.sc_parse(StreamHandler.new(block), data, options)
  else
    to_enum(:read, data, options)
  end
end

#write(data, output_io, options = {}) ⇒ IO, String

Writes objects to JSON using a streaming mechanism in Oj.

If an IO is provided as output_io then the encoded JSON will be written directly to it and returned from the method.

If an IO is not provided (i.e. nil) then the encoded JSON String will be returned.

was provided as an argument, otherwise a JSON-encoded String is returned

Parameters:

  • data (Hash, Array, Object)

    the objects to encode as JSON

  • output_io (IO)

    the IO to write the encoded JSON to

  • options (Hash) (defaults to: {})

    supplemental options to Oj; default is to set the :mode option to :compat

Returns:

  • (IO, String)

    an IO of encoded JSON is returned if it



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/bel/json/adapter/oj.rb', line 49

def write(data, output_io, options = {})
  options = {
    :mode => :compat
  }.merge!(options)

  if output_io
    # write json and return IO
    Oj.to_stream(output_io, data, options)
    output_io
  else
    # return json string
    string_io = StringIO.new
    Oj.to_stream(string_io, data, options)
    string_io.string
  end
end