Class: PDK::Util::JSONFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/pdk/util/json_finder.rb

Overview

Processes a given string, looking for JSON objects and parsing them.

Examples:

A string with a JSON object and some junk characters

PDK::Util::JSONFinder.new('foo{"bar":1}').objects
=> [{ 'bar' => 1 }]

A string with mulitple JSON objects

PDK::Util::JSONFinder.new('foo{"bar":1}baz{"gronk":2}').objects
=> [{ 'bar' => 1 }, { 'gronk' => 2 }]

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ PDK::Util::JSONFinder

Creates a new instance of PDK::Util::JSONFinder.

Parameters:

  • string (String)

    the string to find JSON objects inside of.



18
19
20
21
22
# File 'lib/pdk/util/json_finder.rb', line 18

def initialize(string)
  require 'strscan'

  @scanner = StringScanner.new(string)
end

Instance Method Details

#objectsArray[Hash]

Returns the parsed JSON objects from the string.

Returns:

  • (Array[Hash])

    the parsed JSON objects present in the string.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/pdk/util/json_finder.rb', line 27

def objects
  return @objects unless @objects.nil?

  require 'json'

  until @scanner.eos?
    @scanner.getch until @scanner.peek(1) == '{' || @scanner.eos?

    (@objects ||= []) << begin
      JSON.parse(read_object(true) || '')
    rescue JSON::ParserError
      nil
    end
  end

  return [] if @objects.nil?

  @objects = @objects.compact
end