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?

1
  • The to_json will do the conversion from ruby to json. I can't quite get what your problem is. Commented Jun 24, 2014 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, my friend. I finally did it. I post my code now.
You're welcome. If this solution worked for you, please accept the answer so others know the question is answered.
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 %>);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.