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,
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
I don't see the problem here. Just make it via ||
operator:
def as_json(opts = {})
{
:type => 'relationship',
:id => id || '',
:followed_id => followed_id || ''
}
end
using below method you will get modified hash or json object. it will replace blank string with nill. need to pass the hash in parameter.
def json_without_null(json_object)
if json_object.kind_of?(Hash)
json_object.as_json.each do |k, v|
if v.nil?
json_object[k] = ""
elsif v.kind_of?(Hash)
json_object[k] = json_without_null(v)
elsif v.kind_of?(Array)
json_object[k] = v.collect{|a| json_without_null(a)}
end
end
end
json_object
end