0

I'm currently trying to return multiple JSON objects in one of my controllers as such.

  @chromosomes = @organism.chromosomes.to_json
  @file_data = current_user.files.to_json
  respond_to do |format|
    format.html
  end

However, on the front end when I do:

 <%= @chromosomes %>

or

  <%= @file_data %>

I don't get a JSON object, instead I get the data as a string with things such as &quote, etc. I've tried parsing the string such as

console.log($.parseJSON("<%= @chromosomes %>"));

but it still isn't working. Is this is because the request being sent back is html?

Thanks!

1
  • You've edited the question, but the answer is still the same, see below... Commented Apr 9, 2012 at 14:31

4 Answers 4

2

Your code should look something like this,

respond_to do |format|
    format.html index.html.erb
    format.xml  { render :xml => @organism.chromosomes) }
    format.json { render :json => @organism.chromosomes) }
end
Sign up to request clarification or add additional context in comments.

Comments

0

You just need

render :json => @organism.chromosomes

By looked at you edit, I think what you want is below:

console.log($.parseJSON("<%= raw @chromosomes %>"));

1 Comment

Thanks, but, I'm still not getting a json object on the front end when I output it. I've updated the question with further details. Thanks again!
0

The problem ended up lying in the fact that Rails encoded the json data as a string, which is the default. To fix the issue I used

 <%= @chromosomes.html_safe %>

on the front end. Further info about this can be found here:

Weird JSON Javascript problem in Rails

Comments

0

This should work, for Rails 2,

console.log($.parseJSON(<%= @chromosomes.dump %>));

for Rails 3,

console.log($.parseJSON(<%= @chromosomes.dump.html_safe %>));

String#dump escapes the characters and makes parseJSON() work. Notice that no quotation marks needed.

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.