Search code examples
rubyjsonhashpretty-print

Display formatted hash in browser using Ruby


I am writing a ruby gem that will create an HTML file. I am writing a hash to that. I wanted this hash to be displayed like a formatted json structure. But when I open it on browser it just display as a String. How can I format the hash and display it on the browser.

I tried the following things,

file.write(my_hash.to_json)

file.write(PP.pp(my_has))

file.write(JSON.pretty_generate(my_hash))

Solution

  • my_hash.map do |key,value|
      "#{ key }:#{ value }"
    end.join( '<br>' )
    

    or

    my_hash.map do |key,value|
      "<span>#{ key }:#{ value }</span>"
    end.join( "\n" )