I created a REST API with rails and use .to_json to convert the API output to json response. E.g. @response.to_json

The objects in the response contains created_at and updated_at fields, both Datetime

In the JSON response, both these fields are converted to strings, which is more costly to parse than unixtimestamp.

Is there a simple way I can convert the created_at and updated_at fields into unixtimestamp without having to iterate through the whole list of objects in @response?

[updated] danielM's solution works if it's a simple .to_json. However, if I have a .to_json(:include=>:object2), the as_json will cause the response to not include object2. Any suggestions on this?

有帮助吗?

解决方案

Define an as_json method on your response model. This gets run whenever you return an instance of the response model as JSON to your REST API.

def as_json(options={})
    {
        :id => self.id,
        :created_at => self.created_at.to_time.to_i,
        :updated_at => self.updated_at.to_time.to_i
    }
end

You can also call the as_json method explicitly to get the hash back and use it elsewhere.

hash = @response.as_json

Unix timestamp reference: Ruby/Rails: converting a Date to a UNIX timestamp

Edit: The as_json method works for relationships as well. Simply add the key to the hash returned by the function. This will run the as_json method of the associated model as well.

def as_json(options={})
    {
        :id => self.id,
        :created_at => self.created_at.to_time.to_i,
        :updated_at => self.updated_at.to_time.to_i,
        :object2 => self.object2,
        :posts => self.posts
    }
end

Furthermore, you can pass in parameters to the method to control how the hash is built.

def as_json(options={})
    json = {
        :id => self.id,
        :created_at => self.created_at.to_time.to_i,
        :updated_at => self.updated_at.to_time.to_i,
        :object2 => self.object2
    }

    if options[:posts] == true
        json[:posts] = self.posts
    end
    json
end

hash = @response.as_json({:posts => true})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top