Puppet Function: to_sorted_json

Defined in:
lib/puppet/functions/to_sorted_json.rb
Function type:
Ruby 4.x API

Overview

to_sorted_json(Hash $arg)Any

Parameters:

  • arg (Hash)

Returns:

  • (Any)


13
14
15
16
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
# File 'lib/puppet/functions/to_sorted_json.rb', line 13

Puppet::Functions.create_function(:to_sorted_json) do
  dispatch :to_sorted_json do
    param 'Hash', :arg
  end

  def sorted_generate(obj)
    case obj
    when Integer, Float, TrueClass, FalseClass, NilClass
      return obj.to_json
    when String
      obj.to_json
    when Array
      array_ret = []
      obj.each do |a|
        array_ret.push(sorted_generate(a))
      end
      '[' << array_ret.join(',') << ']'
    when Hash
      ret = []
      obj.keys.sort.each do |k|
        ret.push(k.to_json << ':' << sorted_generate(obj[k]))
      end
      '{' << ret.join(',') << '}'
    else
      raise Exception('Unable to handle object of type <%s>' % obj.class.to_s)
    end
  end

  def to_sorted_json(h)
    sorted_generate(h)
  end
end