How to use JavaScript to parse Ruby JSON string

I am trying to get a JSON object from a JSON output string from a Rails application. Currently in JavaScript I am doing:

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

      

However, since there are quotes at the beginning and end of the JSON object, it does not appear as a JSON object. Instead, it does something like

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

      

Is there a way to strip the leading and trailing quotes so that the object is treated as an array instead of a string?

+3


source to share


5 answers


Why don't you do:

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

      

Sidenote:



Hopefully you can do something like:

@chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json

      

+7


source


If you are using jQuery you can do the following



var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');

      

+1


source


Use eval:

var dataObject = eval ('(' + dataString + ')');

0


source


Use an object JSON

that is included in most browsers, or if you are using jQuery, use a method $.jsonParse

that tries to use the object JSON

if it is otherwise defined, parsing with eval

or in a safer way.

0


source


On the controller

@my_var = MyObj.find_by_id(4).to_json

      

On the page in haml mode.

var my_json = $.parseJSON("#{j @my_var}"); //used JQuery to parser JSON string

      

0


source







All Articles