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:
{"id":124,"period_start":null,"period_end":null,"user_id":null,"created_at":"2015-01-04T05:54:05.133Z","updated_at":"2015-01-04T05:54:05.133Z","onscreen_people_rank_lower":null,"onscreen_people_rank_upper":null,"incl_onscreen_people_unranked":null,"offscreen_people_rank_lower":null,"offscreen_people_rank_upper":null,"incl_offscreen_people_unranked":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格式,并引发错误