Class: JsonChecker::JSONValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/json_checker/json_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.validate_with_config(config) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/json_checker/json_validator.rb', line 10

def self.validate_with_config(config)
  
  files = config['files']
  
  if files.nil? || files.empty?
    puts "[ERROR] Invalid json"
    return
  end
  
  files.each do |file|
    fileToCheck = JSONToCheck.new(file)
    
    fileContent = fileToCheck.get_content()   
    
    unless fileToCheck.keys.nil?
      title = "Validating #{fileToCheck.name} values"
      jsonValidator = JSONValidator.new()
      jsonValidator.validate_JSON_with_keys(title, fileToCheck.keys, fileContent)
    end
    
    unless fileToCheck.compareTo.nil?
      JSONComparator.compare(fileToCheck, fileToCheck.compareTo)
    end
  end
  HTMLOutput.generate_output()
end

Instance Method Details

#is_numeric?(obj) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/json_checker/json_validator.rb', line 53

def is_numeric?(obj) 
 obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end

#validate_JSON_with_keys(title, jsonKeys, json) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/json_checker/json_validator.rb', line 37

def validate_JSON_with_keys(title, jsonKeys, json)
    items = Array.new()
    jsonKeys.keys.each do |key|
        value = value_for_key(key, json)
        expected = jsonKeys[key]
        items << verify_value(expected, value, key)
    end
    if items.size > 0
      HTMLOutput.add_validation_item(title, items)
    end
end

#value_for_key(key, json) ⇒ Object



49
50
51
# File 'lib/json_checker/json_validator.rb', line 49

def value_for_key(key, json)
    return value_for_key_with_split_character(key, json, '.')
end

#value_for_key_with_split_character(key, json, splitCharacter) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/json_checker/json_validator.rb', line 57

def value_for_key_with_split_character(key, json, splitCharacter)
    value = json
    key.split(splitCharacter).each do |item|
        if !value.nil? && !item.empty?
          value = is_numeric?(item) ? value[item.to_i] : value[item]
        end
    end
    return value
end

#verify_value(expected, value, key) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/json_checker/json_validator.rb', line 67

def verify_value(expected, value, key)
    formatter = "<tr><td>%{first}</td><td>%{second}</td><td>%{third}</td><td>%{fourth}</td></tr>"
    result = "Error"
    if value.nil?
      result = "Not found"
    elsif value == expected
      result = "Success"
    end
    return formatter % {first: result, second: key, third:expected, fourth:value}
end