Class: OneApi::JSONUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/oneapi-ruby/utils.rb

Class Method Summary collapse

Class Method Details

.get(json, field) ⇒ Object



17
18
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
# File 'lib/oneapi-ruby/utils.rb', line 17

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



9
10
11
12
13
14
15
# File 'lib/oneapi-ruby/utils.rb', line 9

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

    return json
end