从Json响应

时间:2016-12-08 23:20:44

标签: ruby-on-rails json rest response

我有一个REST服务,其响应结构因请求中的某些属性而异。从我的代码中,我根据发送给控制器的响应返回不同的类对象(不是ActiveRecord对象)。从控制器获得的响应中,某些属性需要作为响应中的头传递。但是应该从响应机构中删除。如何从类对象中删除它?

假设我对控制器的响应可能是class1对象,其属性为:attr1,attr2,attr3

现在attr3实际上应该在响应头中,所以这适用: response.headers [" Headertitle&#34] = attr3

但我的json响应应该只有attr1,attr2。

另一种情况可能是对控制器的响应是带有attr1,attr3,attr4,attr5的class2对象。 attr3也可以转到响应头。而且反应不应该有attr3。

attr3的值取决于某些业务规则,并根据要求而有所不同。但是每个响应都需要在响应标头中有attr3,而不是在正文中。

如何从响应中删除attr3?

我已经尝试过了:

format.json {render:json => json_response.to_json(除了:[" attr3"])}

这不起作用。

2 个答案:

答案 0 :(得分:1)

您可以使用Ruby Hash slice方法:

all = {name: "Zulh", email: "zulh@example.com", phone: "0123456789"}
=> {:name=>"Zulh", :email=>"zulh@example.com", :phone=>"0123456789"}

selected = all.slice(:name, :email)
=> {:name=>"Zulh", :email=>"zulh@example.com"}

selected.to_json
=> "{\"name\":\"Zulh\",\"email\":\"zulh@example.com\"}"

或者,如果您更喜欢except,这是正确的方法:

all = {name: "Zulh", email: "zulh@example.com", phone: "0123456789"}
=> {:name=>"Zulh", :email=>"zulh@example.com", :phone=>"0123456789"}

selected = all.except(:phone)
=> {:name=>"Zulh", :email=>"zulh@example.com"}

selected.to_json
=> "{\"name\":\"Zulh\",\"email\":\"zulh@example.com\"}"

答案 1 :(得分:0)

如果您使用的是Rails5。

您可以执行以下操作:

    def send_auth_token_for_valid_login_of(user)
      render json: { user: user }, :except =>  [:password_digest, :token_created_at, :reset_password_token, :reset_password_sent_at]
    end