1

In Rails, I'd like to parse an array like below to JSON:

[{:title=>"eltitulo", :start=>"2014-06-12", :end=>"2014-06-14"}]

I have tried to use @myarray.to_json. How can I do it?

ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
user3402629
  • 59
  • 2
  • 9

1 Answers1

3

It sounds like you want a JSON representation of a ruby array. You're on the right track with calling .to_json.

[1] pry(main)> a = [{:title=>"eltitulo", :start=>"2014-06-12", :end=>"2014-06-14"}]
=> [{:title=>"eltitulo", :start=>"2014-06-12", :end=>"2014-06-14"}]
[2] pry(main)> a.to_json
=> "[{\"title\":\"eltitulo\",\"start\":\"2014-06-12\",\"end\":\"2014-06-14\"}]"

As you can see my .to_json call has turned the ruby array into a JSON string. Now if you want to get this JSON string into JavaScript you'll need to output it into your script block with ERB:

<script type="text/javascript">
  my_objects = jQuery.parseJSON(<%=raw @myarray.to_json %>);
</script>

The jQuery.parseJSON() bit assume you're using jQuery, and comes from this StackOverlfow post.

You may also want to look into using e.g. the gon gem for passing data from your controller into your javascript.

Community
  • 1
  • 1
pdobb
  • 17,688
  • 5
  • 59
  • 74
  • Thanks, my friend. I finally did it. I post my code now. – user3402629 Jun 24 '14 at 13:12
  • You're welcome. If this solution worked for you, please accept the answer so others know the question is answered. – pdobb Jun 24 '14 at 13:41
  • I think this code `my_objects = jQuery.parseJSON(<%=raw @myarray.to_json %>);` will be converted to something like this: `my_objects = jQuery.parseJSON([{"title":"eltitulo","start":"2014-06-12","end":"2014-06-14"}]);`. So, if the string is safe (no user input part in it), you can use `my_objects = <%=raw @myarray.to_json %>;` or you can use `my_objects = jQuery.parseJSON(<%=raw @myarray.to_json.inspect %>);` – rubyprince Jun 24 '14 at 14:09