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,
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With