Class: InfobipApi::JSONUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/infobipapi/utils.rb

Class Method Summary collapse

Class Method Details

.get(json, field) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/infobipapi/utils.rb', line 19

def self.get(json, field)
    json = JSONUtils.get_json(json)

    if not field
        return nil
    end

    if field.instance_of? Symbol
        field = field.to_s
    end

    if field.include?('|') then
        field_parts = field.split('|')
        for field_part in field_parts
            value = JSONUtils.get(json, field_part.strip)
            if value
                return value
            end
        end
        return nil
    end

    result = nil
    parts = field.split('.')
    result = json
    for part in parts
        if result == nil
            return nil
        end

        if part.to_i.to_s == part
            # Int index => array:
            result = result[part.to_i]
        else
            # Hash:
            result = result[part]
        end
    end

    result
end

.get_json(json) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/infobipapi/utils.rb', line 11

def self.get_json(json)
    if json.instance_of? String
        return JSON.parse(json)
    end

    return json
end