Class: MSFL::Parsers::JSON

Inherits:
Object
  • Object
show all
Defined in:
lib/msfl/parsers/json.rb

Class Method Summary collapse

Class Method Details

.arrays_to_sets(obj) ⇒ Object

Converts Ruby Arrays in a partially parsed Ruby MSFL filter to MSFL::Types::Set objects

Parameters:

  • obj (Object)

    the object in which to convert Ruby Array objects to MSFL::Types::Set objects

Returns:

  • (Object)

    the result of converting Ruby Arrays to MSFL::Types::Set objects



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/msfl/parsers/json.rb', line 23

def self.arrays_to_sets(obj)
  obj = Types::Set.new obj if obj.is_a?(::Array)
  if obj.respond_to? :each
    if obj.is_a?(::Hash)
      result = {}
      obj.each { |key, val| result["#{key}".to_sym] = arrays_to_sets val }
    elsif obj.is_a?(Types::Set)
      result = Types::Set.new obj.map { |value| arrays_to_sets value }
    end
  end
  result ||= obj
  result
end

.convert_keys_to_symbols(obj) ⇒ Object

Deeply converts all hash keys to symbols

Parameters:

  • obj (Object)

    the object on which to deeply convert hash keys to symbols

Returns:

  • (Object)

    the object with its hash keys deeply converted to symbols



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/msfl/parsers/json.rb', line 41

def self.convert_keys_to_symbols(obj)
  result = obj
  if obj.is_a? Hash
    result = Hash.new
    obj.each do |k, v|
      value = convert_keys_to_symbols v
      result["#{k}".to_sym] = value
    end
  elsif obj.is_a? Types::Set
    result = Types::Set.new
    obj.each do |v|
      result << convert_keys_to_symbols(v)
    end
  elsif obj.is_a? Array # Generally this will not be the case as the expectation is that arrays_to_sets has already run
    result = convert_keys_to_symbols(arrays_to_sets(obj))
  end
  result
end

.parse(json) ⇒ Object

Parses json encoded MSFL into Ruby encoded MSFL

Parameters:

  • json (String)

    the string to parse

Returns:

  • (Object)

    the Ruby encoded MSFL, which may be a Hash, MSFL::Types::Set, or any number of scalar types



10
11
12
13
14
15
16
17
# File 'lib/msfl/parsers/json.rb', line 10

def self.parse(json)
  json_to_parse = json
  json_to_parse = '{}' if json_to_parse.nil? || json_to_parse == "" || json_to_parse == "null"
  obj = ::JSON.parse(json_to_parse)
  obj = arrays_to_sets obj
  obj = convert_keys_to_symbols obj
  obj
end