Class: Artificial::Parsers::JSONParser

Inherits:
Object
  • Object
show all
Defined in:
lib/artificial/parsers/json_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ JSONParser

Returns a new instance of JSONParser.



10
11
12
13
14
# File 'lib/artificial/parsers/json_parser.rb', line 10

def initialize(input)
  @input = input
  @parsed_data = {}
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



8
9
10
# File 'lib/artificial/parsers/json_parser.rb', line 8

def errors
  @errors
end

#inputObject (readonly)

Returns the value of attribute input.



8
9
10
# File 'lib/artificial/parsers/json_parser.rb', line 8

def input
  @input
end

#parsed_dataObject (readonly)

Returns the value of attribute parsed_data.



8
9
10
# File 'lib/artificial/parsers/json_parser.rb', line 8

def parsed_data
  @parsed_data
end

Instance Method Details

#parseObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/artificial/parsers/json_parser.rb', line 16

def parse
  return self unless valid?

  begin
    json_data = JSON.parse(@input)
    @parsed_data = normalize_json_data(json_data)
    @parsed_data[:format] = 'json'
    @parsed_data[:type] = 'structured_json'
  rescue JSON::ParserError => e
    @errors << "JSON parsing error: #{e.message}"
  rescue StandardError => e
    @errors << "JSON processing error: #{e.message}"
  end

  self
end

#to_hashObject



49
50
51
# File 'lib/artificial/parsers/json_parser.rb', line 49

def to_hash
  @parsed_data
end

#valid?Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/artificial/parsers/json_parser.rb', line 33

def valid?
  return false unless @input.is_a?(String)
  return false if @input.strip.empty?

  begin
    JSON.parse(@input)
    true
  rescue JSON::ParserError => e
    @errors << "Invalid JSON: #{e.message}"
    false
  rescue StandardError => e
    @errors << "JSON validation error: #{e.message}"
    false
  end
end