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?
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?
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.
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 %>);