0

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?

1
  • What type is chromosomes? Is it a raw string (and if so, why)? Does it come from to_json? Other? Commented Jul 9, 2015 at 6:11

3 Answers 3

1

Use JSON.parse to parse string into JSON object.

data = JSON.parse('<%= @chromosomes%>');
Sign up to request clarification or add additional context in comments.

1 Comment

Not safe for ' or </script etc. (There has to be some 'universal' solution..)
1

Use html_safe in the view, no quotes:

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

3 Comments

Can potentially lead to problems with escaping (or lack of), same as with the other current answers.
how? in the question, it says, JSON outputted string, so, I am expecting in controller he is using @chromosomes.to_json
Assumptions are assumptions .. I asked the OP for clarification. In any case it would still fail on </script. As with all my comments I am trying to elicit some One True For All Time approach.
1

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.

Comments

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.