Suggest different variables to use if we want to tunnel both v4 and v6
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / functions / to_json_pretty.rb
1 # Take a data structure and output it as pretty JSON
2 #
3 # @example how to output pretty JSON
4 #   # output pretty json to a file
5 #     file { '/tmp/my.json':
6 #       ensure  => file,
7 #       content => to_json_pretty($myhash),
8 #     }
9 #
10 # @example how to output pretty JSON skipping over keys with undef values
11 #   # output pretty JSON to a file skipping over undef values
12 #     file { '/tmp/my.json':
13 #       ensure  => file,
14 #       content => to_json_pretty({
15 #         param_one => 'value',
16 #         param_two => undef,
17 #       }),
18 #     }
19 #
20 require 'json'
21
22 Puppet::Functions.create_function(:to_json_pretty) do
23   dispatch :to_json_pretty do
24     param 'Variant[Hash, Array]', :data
25     optional_param 'Boolean', :skip_undef
26   end
27
28   def to_json_pretty(data, skip_undef = false)
29     if skip_undef
30       if data.is_a? Array
31         data = data.reject { |value| value.nil? }
32       elsif data.is_a? Hash
33         data = data.reject { |_, value| value.nil? }
34       end
35     end
36     JSON.pretty_generate(data) << "\n"
37   end
38 end