summaryrefslogtreecommitdiff
path: root/puppet/lib/puppet/parser/functions/sorted_json.rb
blob: 605da00e03c12b94fffe1edbf3af35ece4a501aa (plain)
1
2
3
4
5
6
7
8
9
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
36
37
38
39
40
41
42
43
44
45
46
47
#
# Written by Gavin Mogan, from https://gist.github.com/halkeye/2287885
# Put in the public domain by the author.
#

require 'json'

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

module Puppet::Parser::Functions
  newfunction(:sorted_json, :type => :rvalue, :doc => <<-EOS
This function takes data, outputs making sure the hash keys are sorted

*Examples:*

    sorted_json({'key'=>'value'})

Would return: {'key':'value'}
    EOS
  ) do |arguments|
    raise(Puppet::ParseError, "sorted_json(): Wrong number of arguments " +
      "given (#{arguments.size} for 1)") if arguments.size != 1

    json = arguments[0]
    return sorted_json(json)
  end
end