Pretty print a JSON object created in Ruby to Chrome browser console

I'm parsing a Ruby object into JSON, rendering it in a js.erb file, and printing it to console (Chrome Browser).

In my js.erb file, when I print this:

console.log("<%= @search.attributes.to_json %>")

I get this:

{&quot;id&quot;:124,&quot;period_start&quot;:null,&quot;period_end&quot;:null,&quot;user_id&quot;:null,&quot;created_at&quot;:&quot;2015-01-04T05:54:05.133Z&quot;,&quot;updated_at&quot;:&quot;2015-01-04T05:54:05.133Z&quot;,&quot;onscreen_people_rank_lower&quot;:null,&quot;onscreen_people_rank_upper&quot;:null,&quot;incl_onscreen_people_unranked&quot;:null,&quot;offscreen_people_rank_lower&quot;:null,&quot;offscreen_people_rank_upper&quot;:null,&quot;incl_offscreen_people_unranked&quot;:null}

which is very hard to read. I want to make the JSON pretty so that I can read it more easily.

In my js.erb file, I've tried this:

console.log(eval("(" + "<%= @search.attributes.to_json %>" + ")"))

and this:

console.log( jQuery.parseJSON("<%= @search.attributes.to_json %>") )

and this:

console.log( "<%= JSON.pretty_generate(@search.attributes) %>" )

but none work--the code is not evaluated and nothing is outputted. What am I doing wrong?


Expanding on Cba Bhusal's answer, this worked for me the best:

console.log("<%= j JSON.pretty_generate(@search.attributes).html_safe %>");

The escape_javascript was needed to escape quotes, while the JSON.pretty_generate inserted whitespace to make it even prettier. The output in Chrome console looks like this:

{
  "id": 138,
  "user_id": null,
  "created_at": "2015-01-04T15:57:23.110Z",
  "updated_at": "2015-01-04T15:57:23.110Z"
  #...
}

它很简单,试试这个

console.log("<%= @search.attributes.to_json.html_safe %>")
链接地址: http://www.djcxy.com/p/47162.html

上一篇: 如何呈现正确的JSON格式,并引发错误

下一篇: 漂亮打印在Ruby到Chrome浏览器控制台中创建的JSON对象