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
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
要添加到 philee 的答案,您可以在模型中添加一个 as_json 方法。
def as_json(opts={})
json = super(opts)
Hash[*json.map{|k, v| [k, v || "NA"]}.flatten]
end
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\"}"