Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / functions / to_json_pretty.rb
1 require 'json'
2 # @summary
3 #   Convert data structure and output to pretty JSON
4 #
5 # @example **Usage**
6 #   * how to output pretty JSON to file
7 #     file { '/tmp/my.json':
8 #       ensure  => file,
9 #       content => to_json_pretty($myhash),
10 #     }
11 #
12 #   * how to output pretty JSON skipping over keys with undef values
13 #     file { '/tmp/my.json':
14 #       ensure  => file,
15 #       content => to_json_pretty({
16 #         param_one => 'value',
17 #         param_two => undef,
18 #       }),
19 #     }
20 Puppet::Functions.create_function(:to_json_pretty) do
21   # @param data
22   #   data structure which needs to be converted to pretty json
23   # @param skip_undef
24   #   value `true` or `false`
25   # @return
26   #   converted data to pretty json
27   dispatch :to_json_pretty do
28     param 'Variant[Hash, Array]', :data
29     optional_param 'Boolean', :skip_undef
30   end
31
32   def to_json_pretty(data, skip_undef = false)
33     if skip_undef
34       if data.is_a? Array
35         data = data.reject { |value| value.nil? }
36       elsif data.is_a? Hash
37         data = data.reject { |_, value| value.nil? }
38       end
39     end
40     JSON.pretty_generate(data) << "\n"
41   end
42 end