tim_xyz
tim_xyz

Reputation: 13551

What causes a JSON response to be surrounded by quotes?

I've setup an API endpoint in App1 and am posting to it to create a user record from App2.

I've set App1 to respond with JSON but the JSON response is surrounded quotes (and filled with backslashes). I understand backslashes are used to escape quotes but it still seems weird.

Expected response

{id:8, first_name:"Long", last_name:"John Silver", email:"[email protected]", temp_password:"ydKrDdd9zbrGzrm-uMK8"}

Actual response

"{\"id\":8,\"first_name\":\"Long\",\"last_name\":\"John Silver\",\"email\":\"[email protected]\",\"temp_password\":\"ydKrDdd9zbrGzrm-uMK8\"}"

Routes

namespace :api do
  namespace :v1 do
    resources :users, :defaults => { :format => 'json' }
  end
end

Controller

def create
    @user = User.new(user_params)
    @user.temp_password = Devise.friendly_token
    if @user.save
        render json: @user
    else
        render json: {res: "Something went wrong"}
    end
end

def user_params
  params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :temp_password)
end

Is it possible to get a response like "expected response" above? What might be causing this?

Thanks kindy.

Upvotes: 2

Views: 407

Answers (1)

Graham Slick
Graham Slick

Reputation: 6870

You can use:

 JSON.parse(response)

to get what you expected. Depending on your setup and where the request is coming from, you might have to use:

JSON.parse(response).with_indifferent_access 

To be able to use quotes or symbols.

Upvotes: 4

Related Questions