[英]How to serialize nil to JSON as nil, not an empty place?
In my controller/action I have some values that are nil 在我的控制器/动作中,我有一些零值
def my_action
@var1 = get_boolean_value || nil
@var2 = get_int_value || nil
@var3 = get_string_value || nil
# there many more, any one can happen to be nil
end
When I create a JSON object in a view out of them, nil values get rendered as an empty space: 当我在其中的视图中创建JSON对象时,nil值将呈现为空白空间:
:javascript
window.MyObj = {
var1: #{@var1},
var2: #{@var1},
var2: #{@var3}
}
The issue is that when a value is nil, it's rendered as an empty space, not nil itself. 问题是,当值是nil时,它将被呈现为空白空间,而不是nil本身。
:javascript
window.MyObj = {
var1: ,
var2: 33,
var2:
}
How to cure that? 怎么治呢?
One should not reinvent the wheel. 一个人不应该重新发明轮子。 Use
JSON
ruby standard library to serialize json: 使用
JSON
ruby标准库序列化json:
require 'json'
json = {var1: nil, var2: 42, var2: nil}.to_json
#⇒ "{\"var1\":null,\"var2\":42,\"var3\":null}"
and then: 接着:
:javascript
window.MyObj = json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.