如何在CHEF(Ruby)中创建漂亮的json
您将如何制作一个具有人类可读json的erb模板?
How would you make an erb template that has human readable json?
以下代码可以正常工作,但是可以创建一个平面json文件
The following code works, but it makes a flat json file
default.rb
default.rb
default['foo']['bar'] = { :herp => 'true', :derp => 42 }
recipe.rb
recipe.rb
template "foo.json" do
source 'foo.json.erb'
variables :settings => node['foo']['bar'].to_json
action :create
end
foo.json.erb
foo.json.erb
<%= @settings %>
类似的SO问题
Chef和ruby模板-如何遍历键值对?
如何漂亮
此SO Answer .erb模板适用于HTML和XML,但不适用于json。
As pointed out by this SO Answer .erb templates are great for HTML, and XML, but is not good for json.
幸运的是,CHEF使用了它的拥有自己的json库,它使用 .to_json_pretty
Luckily, CHEF uses its own json library which has support for this using .to_json_pretty
本文将更广泛地显示如何在食谱中使用厨师助手。
@coderanger in IRC, pointed out that you can use this library right inside the recipe. This article shows more extensively how to use chef helpers in recipes.
default.rb
default.rb
# if ['foo']['bar'] is null, to_json_pretty() will error
default['foo']['bar'] = {}
食谱/foo.rb
pretty_settings = Chef::JSONCompat.to_json_pretty(node['foo']['bar'])
template "foo.json" do
source 'foo.json.erb'
variables :settings => pretty_settings
action :create
end
YMMV指出的或更简洁
Or more concise as pointed out by YMMV
default.rb
default.rb
# if ['foo']['bar'] is null, to_json_pretty() will error
default['foo']['bar'] = {}
recipe / foo.rb
recipe/foo.rb
template "foo.json" do
source 'foo.json.erb'
variables :settings => node['foo']['bar']
action :create
end
templates / foo.json.erb
templates/foo.json.erb
<%= Chef::JSONCompat.to_json_pretty(@settings) %>