Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JavaScript to parse Ruby JSON string

I'm trying to get the JSON object from a JSON outputted string from a Rails app. Currently in JavaScript I'm doing:

data = "<%= @chromosomes.html_safe %>";

However, since there are quotes at the beginning and end of the JSON object, it is not being rendered as a JSON object. Instead it is doing something like

 data = "[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]"

Is there a way that I can remove the beginning and end quotes so that the object is treated as an array instead of a string?

like image 737
Phillip Whisenhunt Avatar asked Apr 09 '12 14:04

Phillip Whisenhunt


2 Answers

Why don't you do:

data = <%= @chromosomes.html_safe %>;

Sidenote:

I hope you do something like:

@chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
like image 66
apneadiving Avatar answered Sep 20 '22 16:09

apneadiving


If you are using jQuery you can do the following

var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
like image 41
Two Seeds Avatar answered Sep 18 '22 16:09

Two Seeds