JSON render problem

Hi all,

In my controller, I have an action to render JSON string containing current user's account information, except for his ID and hashed password. This is the snippet:

# Fetch the account information of the current user def fetch_data

  record = User.find session[:user_id]

  render :json =>   {     :success => true,     :data => (record.to_json(:except => [:id, :password]))   } end

It does not work. The :data attribute contains a JSON string instead of an object. Sample output:

{"success":true,"data":"{\"name\":\"The Administrator\",\"username\":\"admin\",\"role\":\"admin\"}"}

How can I fix this?

Thanks.

Conrad Taylor wrote:

The above seems correct based on your render statement. What's the problem?

-Conrad

The data attribute should be an object, not a string. Let's compare the difference with the following snippet:

render :json => {   :success => true,   :data => record # Without to_json method }

The output will be: (the data attribute is an object) {"success":true,"data":{"name":"The Administrator","username":"admin","role":"admin","id":1,"password":"d033e22ae348aeb5660fc2140aec35850c4da997"}}

Instead of: (the data attribute is a string) {"success":true,"data":"{\"name\":\"The Administrator\",\"username\":\"admin\",\"role\":\"admin\"}"}

The problem is, I want to hide several attributes from the output, and the only method that I know is to use :except parameter from to_json method.

So, my objective is to get the output similiar to output #1, but without the ID and password attribute.

Conrad Taylor wrote:

The above seems correct based on your render statement. What’s the

problem?

-Conrad

The data attribute should be an object, not a string.

Let’s compare the difference with the following snippet:

From the JSON specification, http://www.json.org/, an object in JSON consists of name/value pairs. The object here is “data” and you should be able to easily access

this information on the client side.

Next, you can limit which fields get returned from a SQL query using ‘find(:all, :select => “arg1, arg2, …”, … )’.

Finally, the easiest way to convert an AR instance to JSON is to use to_json method on the instance (i.e. object.to_json). Otherwise, you can write a simply method, to_hash or to_h, which returns the hash of the AR. Then you’ll have something like this:

def to_hash

{ :name => self.name, :username => self.username, :role => self.role }

end

render :json => { :success => true, :data => record.to_hash }

Good luck,

-Conrad