【问题标题】:Rendering a hash inside a JSON file with Ruby and ERB ('=>' notation)使用 Ruby 和 ERB('=>' 表示法)在 JSON 文件中呈现哈希
【发布时间】:2015-06-11 20:01:01
【问题描述】:

我正在尝试使用 ERB 呈现 JSON 模板,不幸的是,由于 '=>' 哈希表示法,它不像使用 Python 那样简单。 这是一个简短的例子:

  require 'erb'

  h = Hash.new
  h["first"] = "First"
  h["second"] = "Second"

  template = ERB.new <<-EOF
  {
    "key": "value",
    "foo": 1,
    "Hash": <%= h %>,
    "bar": 2
  }
  EOF

  puts template.result(binding)

这段代码会产生这样的输出:

  {
    "key": "value",
    "foo": 1,
    "Hash": {"first"=>"First", "second"=>"Second"},
    "bar": 2
  }

将 '=>' 符号转换为冒号会生成一个有效的 json 文件。 有没有办法使用我不知道的 Ruby/ERB(除了分别打印键、值和字符)?还是应该对我生成的 json 文件进行替换?

我觉得我错过了明显的解决方案

【问题讨论】:

  • 为什么要使用 ERB 呢?你为什么不建立一个嵌套的哈希和to_json呢?
  • 我不确定我是否有一个聪明的答案!我会考虑一下,如果它真的对我没有好处,我会删除所有冗余。感谢您的评论

标签: ruby json hash erb


【解决方案1】:

您是否正在寻找类似的东西:

require 'erb'
require 'json'

h = Hash.new
h["first"] = "First"
h["second"] = "Second"

template = ERB.new <<-EOF
  {
    "key": "value",
    "foo": 1,
    "Hash": <%= h.to_json %>,
    "bar": 2
  }
EOF

puts template.result(binding)

输出

[arup@Ruby]$ ruby a.rb
  {
    "key": "value",
    "foo": 1,
    "Hash": {"first":"First","second":"Second"},
    "bar": 2
  }
[arup@Ruby]$

【讨论】:

  • 我就知道必须这么简单:) 谢谢!
猜你喜欢
  • 2012-02-15
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多