Rails 3.2: Replace null values with empty string from json serialization

json, ruby, ruby-on-rails, ruby-on-rails-3.2, serialization

Solution

Probably not the best solution, but inspired by this answer

def as_json(opts={})
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

-- Edit --

As per jdoe's comment, if you only want to include some fields in your json response, I prefer doing it as:

def as_json(opts={})
  opts.reverse_merge!(:only => [:type, :id, :followed_id])
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || ""]}.flatten]
end

Problem

I am using Rails 3.2 serialization to convert ruby object to json. For Example, I have serialized ruby object to following json ``` { "relationship":{ "type":"relationship", "id":null, "followed_id": null } } ``` Using following serialize method in my class Relationship < ActiveRecord::Base ``` def as_json(opts = {}) { :type => 'relationship', :id => id, :followed_id => followed_id } end ``` I need to replace null values with empty strings i.e. empty double quotes, in response json. How can I achieve this? Best Regards,

Original source