allenwlee
allenwlee

Reputation: 685

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?

Upvotes: 2

Views: 1115

Answers (2)

allenwlee
allenwlee

Reputation: 685

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"
  #...
}

Upvotes: 2

Shiva
Shiva

Reputation: 12582

its pretty simple, try this

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

Upvotes: 1

Related Questions