Tim
Tim

Reputation: 3221

Rails is changing returned JSON into HTML

When a JSON is returned from an API call in my Rails app I get this response:

"{\"stdout\":\"2\\n\",\"stderr\":\"\",\"wallTime\":241,\"exitCode\":0}"

When it should look like this:

{"stdout": "2\n", "stderr": "", "wallTime": 241, "exitCode": 0}

How do I change this bearing in mind the response is being dealt with in JavaScript?

The JS handling the response:

$(document).ready ->
  $(".edit_code_lesson").on("ajax:success", (e, data, status, xhr) ->
    result = JSON.parse(data)
    alert(result);
  ).bind "ajax:error", (e, xhr, status, error) ->
    console.log(status + '\n ' + error);
    console.log(xhr);

It is after inspecting the xhr I noticed the HTML formatted JSON was being returned. A Syntax error is being thrown.

This is the controller fetching the API:

def evaluate
  @code_lesson = CodeLesson.find(params[:code_lesson][:id])
  @language = Language.find(@code_lesson.language_id).slug
  @sandie = Sandie.new(language: @language)
  @code = @sandie.evaluate(code: params[:code_lesson][:user_code]).to_json
end

Upvotes: 0

Views: 116

Answers (2)

bprayudha
bprayudha

Reputation: 1044

In your controller, do this:

render :json => your_params, :status => 200

Upvotes: 1

thorsten müller
thorsten müller

Reputation: 5661

Where exactly does it appear like that? Already in the controller? Or somewhere on your site after you render it? You can render with

<% raw @some_stuff %>

or

<%== @some_stuff %>

to avoid such conversions. (If @some_stuff is already a string). What do you want to do there? just render it as HTML or generate a JSON object?

Upvotes: 0

Related Questions