Module: JsonHelper

Defined in:
lib/chaoite/json_helper.rb

Instance Method Summary collapse

Instance Method Details

#resolve_json_path(json, template) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/chaoite/json_helper.rb', line 2

def resolve_json_path(json, template)
  if template.start_with?("$") then
    JsonPath.on(json, template)
  else
    paths = template.scan(/(\{(.*?)\})/).uniq
    return template if paths.empty?
    combinations = paths.map { |path| {path[0] => JsonPath.on(json, path[1])} }.reduce(&:merge)

    combinations = combinations.values[0].product(*combinations.values[1..-1]).map{ |x| combinations.keys.zip(x).to_h }

    combinations.map do |c|
      t = template+''
      c.keys.each do |key|
        t.gsub!(key, c[key])
      end
      t
    end
  end
end

#valid_json?(json) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
# File 'lib/chaoite/json_helper.rb', line 22

def valid_json?(json)
  begin
    JSON.parse(json)
    return true
  rescue Exception => e
    return false
  end
end