3

How to change the field values from null to "" in the output of to_json?

It currently returns

{"name":"priya","mobile":null} 

instead I want

{"name":"priya","mobile":""}

or

{"name":"priya","mobile":"NA"}

Please suggest

4

2 回答 2

1

要添加到 philee 的答案,您可以在模型中添加一个 as_json 方法。

def as_json(opts={})
  json = super(opts)
  Hash[*json.map{|k, v| [k, v || "NA"]}.flatten]
end
于 2012-05-30T11:44:52.703 回答
1
s = {"name" => "pryia", "mobile" => nil} 

Hash[*s.map{|k, v| [k, v || "NA"]}.flatten]
# => "name"=>"pryia", "mobile"=>"NA"}

Hash[*s.map{|k, v| [k, v || "NA"]}.flatten].to_json
# => "{\"name\":\"pryia\",\"mobile\":\"NA\"}"
于 2012-05-30T09:52:50.897 回答