Reputation: 63
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%>";
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?
Upvotes: 0
Views: 64
Reputation: 191
data = '<%= @chromosomes%>'; var result = JSON.parse(data);
if you do console.log(result), it outputs a json object. This is a pure JavaScript approach and you require a reasonably modern browser that supports parsing JSON into a native object.
Upvotes: 1
Reputation: 336
Use html_safe in the view, no quotes:
<script>
data = <%= @chromosomes.html_safe %>;
</script>
Upvotes: 1
Reputation: 87203
Use JSON.parse
to parse string
into JSON
object.
data = JSON.parse('<%= @chromosomes%>');
Upvotes: 1