2

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?

allenwlee
  • 665
  • 6
  • 21

2 Answers2

2

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"
  #...
}
Community
  • 1
  • 1
allenwlee
  • 665
  • 6
  • 21
1

its pretty simple, try this

console.log("<%= @search.attributes.to_json.html_safe %>")
Shiva
  • 11,485
  • 2
  • 67
  • 84
  • thanks. for some reason, that didn't work, but this did: `console.log("<%= j @search.attributes.to_json.html_safe %>")`(added j) – allenwlee Jan 04 '15 at 06:13