【问题标题】:How do you create pretty json in CHEF (ruby)你如何在 CHEF (ruby) 中创建漂亮的 json
【发布时间】:2015-09-14 00:22:56
【问题描述】:

您将如何制作具有人类可读 json 的 erb 模板?

以下代码有效,但它生成了一个平面 json 文件

default.rb

default['foo']['bar'] = { :herp => 'true', :derp => 42 }

食谱.rb

template "foo.json" do
  source 'foo.json.erb'
  variables :settings => node['foo']['bar'].to_json
  action :create
end

foo.json.erb

<%= @settings %>

类似的 SO 问题
Chef and ruby templates - how to loop though key value pairs?
How can I "pretty" format my JSON output in Ruby on Rails?

【问题讨论】:

  • 如果你的erb只是一个&lt;%= @something %&gt;,你最好使用file resource

标签: ruby chef-infra erb


【解决方案1】:

正如this SO Answer 所指出的,.erb 模板非常适合 HTML 和 XML,但不适用于 json。

幸运的是,CHEF 使用了它的 own json library,它使用 .to_json_pretty 对此提供了支持

IRC 中的@coderanger 指出你可以在配方中使用这个库。 This article shows more extensively 如何在食谱中使用厨师助手。

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 所指出的那样

default.rb

# if ['foo']['bar'] is null, to_json_pretty() will error
default['foo']['bar'] = {}

食谱/foo.rb

template "foo.json" do
  source 'foo.json.erb'
  variables :settings => node['foo']['bar']
  action :create
end

模板/foo.json.erb

<%= Chef::JSONCompat.to_json_pretty(@settings) %>

【讨论】:

  • 您也应该能够在您的 erb 模板中执行此操作:。我有点喜欢这样,因为它将字符串格式的责任变成了模板中的视图逻辑。 YMMV。
【解决方案2】:

类似的方法也可以:

file "/var/my-file.json" do
  content Chef::JSONCompat.to_json_pretty(node['foo']['bar'].to_hash)
end

【讨论】:

    【解决方案3】:

    &lt;%= Chef::JSONCompat.to_json_pretty(@settings) %&gt; 像魅力一样工作!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-20
      • 2013-05-25
      • 2015-03-02
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      相关资源
      最近更新 更多