gpt4 book ai didi

ruby-on-rails - 使用 Oj.dump 序列化时将符号转换为字符串

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:10 24 4
gpt4 key购买 nike

问题摘要:我正在尝试使用 Oj gem 将散列序列化为 JSON。好像Oj不会自动把hash的符号键转成字符串。我想知道 Oj 是否可以在序列化期间选择“字符串化”?

这是我的哈希示例:

example_hash = 
{:id=>1234,
:asset_number=>"1234-5678",
:latitude=>34.78495,
:longitude=>-92.12899,
:last_tracking_record_id=>123456789,
:bearing=>42,
:threat_level=>:severe}

上面的内容是这样呈现的:

render json: Oj.dump(example_hash)

不幸的是,生成的 JSON 具有与上面完全相同的键,这意味着我需要像这样访问 JavaScript 中的元素:response[:asset_number]。由于客户端代码是几个月前实现的,现在才添加 Oj,我更愿意找到一种在序列化服务器端期间对键进行字符串化的方法。

Oj 有一个名为 symbol_keys 的选项,它是一个 bool 值,但是将它设置为 truefalse 似乎对这方面。

到目前为止我找到的唯一解决方案是按照 this answer 中的建议使用 with_indifferent_access ,但是在某些情况下我有哈希数组;虽然我可以在技术上为该数组中的每个散列调用该方法,但鉴于 Oj 旨在加速 Json 序列化,我更愿意找到一种方法来使用 Oj 本身执行此操作。最后,我想知道 Oj 中是否有一个选项或设置可以在 序列化期间执行此操作。

最佳答案

在我写问题的同时,我找到了答案。由于我无法在 StackOverflow 上找到与此问题相关的任何其他答案(特别是关于 Oj gem),我将保留这篇文章,希望它能帮助处于我情况的其他人。

根据 this previously discussed issue on GitHub ,将选项 mode 设置为 :compat 确实会将符号转换为字符串。所以我的渲染线现在看起来像这样:

render json: Oj.dump(example_hash, mode: :compat)

根据Oj documentation for default_options , :compat模式定义如下:

...compatible with other systems. It will serialize any Object but will check to see if the Object implements a to_hash() or to_json() method. If either exists that method is used for serializing the Object. The to_hash() is more flexible and produces more consistent output so it has a preference over the to_json() method. If neither the to_json() or to_hash() methods exist then the Oj internal Object variable encoding is used.

因此,如果我的解释正确,那么这个解决方案似乎可行,因为它最终使用了 Hash 类的 to_json 方法。

我不确定我是否影响了性能(正面或负面),但至少它使我不必手动调用 with_indifferent_accessto_json一个数组。

更新

关于性能,cmwright做了一些基准测试,并得出了这些结果:

Rehearsal ----------------------------------------------
json 13.990000 0.250000 14.240000 ( 14.257051)
oj default 3.260000 0.230000 3.490000 ( 3.491028)
oj compat 3.360000 0.240000 3.600000 ( 3.593109)
------------------------------------ total: 21.330000sec

user system total real
json 13.740000 0.240000 13.980000 ( 13.992641)
oj default 3.020000 0.230000 3.250000 ( 3.248077)
oj compat 3.060000 0.230000 3.290000 ( 3.286443)

似乎 compat 选项至少与默认的 Oj 选项相当,并且比普通的 'ol to_json 效率高得多。

这是 gist包含基准代码。

关于ruby-on-rails - 使用 Oj.dump 序列化时将符号转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21029157/

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