ruby-on-rails - 是什么导致 JSON 响应被引号包围?

标签 ruby-on-rails json endpoint

我已在 App1 中设置了一个 API 端点,并向其发布消息以从 App2 创建用户记录。

我已将 App1 设置为使用 JSON 进行响应,但 JSON 响应用引号括起来(并用反斜杠填充)。我知道反斜杠用于转义引号,但它仍然看起来很奇怪。

预期响应

{id:8, first_name:"Long", last_name:"John Silver", email:"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3100715449505c415d541f525e5c" rel="noreferrer noopener nofollow">[email protected]</a>", temp_password:"ydKrDdd9zbrGzrm-uMK8"}

实际响应

"{\"id\":8,\"first_name\":\"Long\",\"last_name\":\"John Silver\",\"email\":\"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c5d2c09140d011c0009420f0301" rel="noreferrer noopener nofollow">[email protected]</a>\",\"temp_password\":\"ydKrDdd9zbrGzrm-uMK8\"}"

路线

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

是否有可能得到像上面“预期响应”这样的响应? 可能是什么原因造成的?

谢谢亲爱的。

最佳答案

您可以使用:

 JSON.parse(response)

得到你所期望的。 根据您的设置和请求的来源,您可能必须使用:

JSON.parse(response).with_indifferent_access 

能够使用引号或符号。

关于ruby-on-rails - 是什么导致 JSON 响应被引号包围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487259/

相关文章:

java - 如何使对象返回通用

azure - 设置-AzDataFactoryV2 : A parameter cannot be found that matches parameter name 'PublicNetworkAccess'

ruby-on-rails - 优化 Heroku、Rails 和 Unicorn : defining proper configuration options like how many worker processes?

ruby-on-rails - Rails 文档

ruby-on-rails - rvm 更新 : Your local changes to the following files would be overwritten by merge on rvm get head command 上的 git 错误

c# - json 文件反序列化为 poco 对象不起作用

ruby-on-rails - ActiveRecord 中的自定义范围 - 使用无效语法生成反向排序

json - Flutter/Dart Json序列化

java - HttpException : 500 when running a SPARQL query on remote endpoint

php - 在 WooCommerce 中设置我的帐户自定义项目端点标题