如何在CHEF(Ruby)中创建漂亮的json [英] How do you create pretty json in CHEF (ruby)

查看:41
本文介绍了如何在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) %>

这篇关于如何在CHEF(Ruby)中创建漂亮的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆