Using a different key for to_json: methods

When using :methods in to_json , is there a way to rename the key? I am trying to replace the real id with its base62, and I want the base62_id value base62_id have the key :id .

 @obj.to_json( :except => :id :methods => :base62_id ) 

I tried to do

 @obj.to_json( :except => :id :methods => { :id => :base62_id } ) 

but it didn’t work.

Any tips?

+6
json ruby-on-rails
source share
1 answer

The to_json serializer uses the method name as the key for serialization. Therefore, you cannot use the methods parameter to do this. Unfortunately, the to_json method to_json not have the t accept block` parameter, otherwise you could do something similar to

 @obj.to_json(:except => :id) {|json| json.id = base62_id } 

So this leaves us with an ugly hack, for example:

 def to_json(options={}) oid, self.id = self.id, self.base62_id(self.id) super ensure self.id = oid end 

Now to_json will return the expected result.

+2
source share

All Articles