Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 606
Omer Aslam Avatar asked Dec 06 '25 07:12

Omer Aslam


2 Answers

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
like image 67
jdoe Avatar answered Dec 08 '25 21:12

jdoe


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
like image 30
zsquare Avatar answered Dec 08 '25 20:12

zsquare