gpt4 book ai didi

ruby-on-rails - Rails JSON 十进制序列化添加引号

转载 作者:行者123 更新时间:2023-12-03 05:32:07 25 4
gpt4 key购买 nike

我正在为具有多个小数和整数属性的模型使用默认的 JSON 序列化。结果示例如下:

{ "user": { "id": 1234, "rating": "98.7" } }

请注意“评级”值周围添加的引号。这导致我使用的反序列化库错误地将它们视为字符串(而不是小数)。 Rails 可以设置为不对所有小数使用引号吗?

编辑:

我使用的是 Rails 3.0.7 和 Ruby 1.9.2(如果这有区别的话)。

编辑:

终端:

rails g model user rating:decimal
rake db:migrate

控制台:

user = User.create(rating: 98.7)
user.to_json

最佳答案

将小数从语言 A 传递到语言 B 的唯一“安全”方法是使用字符串。如果您的 json 包含 "rating": 98.79999999999999 它可能会被您的 JavaScript 运行时转换为 98.79999999999998

参见BigDecimal as_json文档:

A BigDecimal would be naturally represented as a JSON number. Most libraries, however, parse non-integer JSON numbers directly as floats. Clients using those libraries would get in general a wrong number and no way to recover other than manually inspecting the string with the JSON code itself.

That’s why a JSON string is returned. The JSON literal is not numeric, but if the other end knows by contract that the data is supposed to be a BigDecimal, it still has the chance to post-process the string and get the real value.

如果你想强制 Rails 不引用这些,你可以给 BigDecimal 打猴子补丁(参见 Rails source )。

# not needed: to compare with the Numeric implementation
class Numeric
def as_json(options = nil) self end #:nodoc:
def encode_json(encoder) to_s end #:nodoc:
end

class BigDecimal
def as_json(options = nil) self end
def encode_json(encoder) to_s end #:nodoc:
end

关于ruby-on-rails - Rails JSON 十进制序列化添加引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6128794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com