Rendering a hash inside a JSON file with Ruby and ERB ('=>' notation)

3.3k views Asked by At

I am trying to render a JSON template using ERB, unfortunately, due to the '=>' hash notation, it's not as simple as it was using Python. Here's a short example:

  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)

This code will produce this output:

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

Converting the '=>' notation to colons will result in a valid json file. Is there a way to so using Ruby/ERB that I'm no aware of (except for printing keys, values and characters separately)? Or should run a substitution on my generated json files?

I feel like I'm missing the obvious solution

1

There are 1 answers

1
Arup Rakshit On BEST ANSWER

Are you looking for something like :

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)

output

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