Skip to main content
The Nameless Site

How to output pretty json in puppet

It kept seeming like it should be straight forward. Various attempts by myself (mostly because I don't know ruby) seemed to fail. I'm just leaving it here now that I figured out how to get it working so I can find it again (and hopefully help others).

init.pp

$config_data = { "foo" => "bar" }

template.erb

<%= require "json"; JSON.pretty_generate config_data %>

I found config_data.to_json wasn't going to work for me because it seemed to output things in different orders each run.

(it was https://snippets.aktagon.com/snippets/412-How-to-pretty-print-JSON-data-with-Ruby that helped me figure this out)

Edit: While pretty, still doesn't sort so puppet can update the config file each run 😦 I will figure this out.

Edit: After much trial and error, I ended writing my own library. https://gist.github.com/2287885

Gist: halkeye/2287885
#
# sorted_json.rb
# Puppet module for outputting json in a sorted consistent way. I use it for creating config files with puppet
require 'json'
def sorted_json(json)
if (json.kind_of? String)
return json.to_json
elsif (json.kind_of? Array)
arrayRet = []
json.each do |a|
arrayRet.push(sorted_json(a))
end
return "[" << arrayRet.join(',') << "]";
elsif (json.kind_of? Hash)
ret = []
json.keys.sort.each do |k|
ret.push(k.to_json << ":" << sorted_json(json[k]))
end
return "{" << ret.join(",") << "}";
end
raise Exception("Unable to handle object of type " + json.class)
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
# vim: set ts=2 sw=2 et :
view raw sorted_json.rb hosted with ❤ by GitHub