Skip to content

Commit 2438d80

Browse files
committed
Backport stdlib::to_json_pretty from upstream
1 parent 69850f4 commit 2438d80

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# frozen_string_literal: true
2+
3+
require 'json'
4+
5+
# @summary
6+
# Convert data structure and output to pretty JSON
7+
#
8+
# @example **Usage**
9+
# * how to output pretty JSON to file
10+
# file { '/tmp/my.json':
11+
# ensure => file,
12+
# content => stdlib::to_json_pretty($myhash),
13+
# }
14+
#
15+
# * how to output pretty JSON skipping over keys with undef values
16+
# file { '/tmp/my.json':
17+
# ensure => file,
18+
# content => stdlib::to_json_pretty({
19+
# param_one => 'value',
20+
# param_two => undef,
21+
# }, true),
22+
# }
23+
#
24+
# * how to output pretty JSON using tabs for indentation
25+
# file { '/tmp/my.json':
26+
# ensure => file,
27+
# content => stdlib::to_json_pretty({
28+
# param_one => 'value',
29+
# param_two => {
30+
# param_more => 42,
31+
# },
32+
# }, nil, {indent => ' '}),
33+
# }
34+
35+
Puppet::Functions.create_function(:'stdlib::to_json_pretty') do
36+
# @param data
37+
# data structure which needs to be converted to pretty json
38+
# @param skip_undef
39+
# value `true` or `false`
40+
# @param opts
41+
# hash-map of settings passed to JSON.pretty_generate, see
42+
# https://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-generate.
43+
# Note that `max_nesting` doesn't take the value `false`; use `-1` instead.
44+
# @return
45+
# converted data to pretty json
46+
dispatch :to_json_pretty do
47+
param 'Variant[Hash, Array]', :data
48+
optional_param 'Optional[Boolean]', :skip_undef
49+
optional_param 'Struct[{
50+
indent => Optional[String],
51+
space => Optional[String],
52+
space_before => Optional[String],
53+
object_nl => Optional[String],
54+
array_nl => Optional[String],
55+
allow_nan => Optional[Boolean],
56+
max_nesting => Optional[Integer[-1,default]],
57+
}]', :opts
58+
end
59+
60+
def to_json_pretty(data, skip_undef = false, opts = nil)
61+
# It's not possible to make an abstract type that can be either a boolean
62+
# false or an integer, so we use -1 as the falsey value
63+
if opts
64+
opts = opts.transform_keys(&:to_sym)
65+
66+
opts[:max_nesting] = false if opts[:max_nesting] == -1
67+
end
68+
69+
data = data.compact if skip_undef && (data.is_a?(Array) || Hash)
70+
# Call ::JSON to ensure it references the JSON library from Ruby's standard library
71+
# instead of a random JSON namespace that might be in scope due to user code.
72+
JSON.pretty_generate(data, opts) << "\n"
73+
end
74+
end

0 commit comments

Comments
 (0)