gpt4 book ai didi

ruby-on-rails - 如何使用 Ruby 将 JSON 时间字符串自动转换为时间对象?

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:19 34 4
gpt4 key购买 nike

当我使用 Ruby 使用返回 JSON 格式的时间字符串的 Web 服务 API 时,我希望它们自动转换为 Time 对象(或 DateTime 对象),因此我自己没有手动完成。

例如,我希望输出 Time 而不是 String:

irb(main):001:0> require 'json'
=> true
irb(main):002:0> payload = JSON.generate({ now: Time.now })
=> "{\"now\":\"2018-04-02 13:15:56 -0500\"}"
irb(main):003:0> JSON.parse(payload)['now'].class
=> String

我知道时间不是 JSON 规范的一部分。我只是想知道是否有一种方法可以配置 Ruby 的 stdlib JSON 解析器来自动解析日期,或者是否有一个库可以为您执行此操作。

最佳答案

当您设置 ActiveSupport.parse_json_times = true 时,Active Support 可以自动将 ISO 8601 格式的时间转换为 ActiveSupport::TimeWithZone 对象。

http://api.rubyonrails.org/classes/ActiveSupport/JSON.html

#!/usr/bin/env ruby

require 'active_support/json'
require 'active_support/time'

Time.zone = 'UTC'
ActiveSupport.parse_json_times = true

puts payload1 = JSON.generate({ now: Time.now })
puts payload2 = ActiveSupport::JSON.encode({ now: Time.now })

puts ActiveSupport::JSON.decode(payload1)['now'].class
puts ActiveSupport::JSON.decode(payload2)['now'].class

输出:

{"now":"2018-04-02 13:19:40 -0500"}
{"now":"2018-04-02T13:19:40.291-05:00"}
String
ActiveSupport::TimeWithZone

请注意 Active Support 无法解析 Ruby stdlib 的默认时间。只有 ISO 8601 格式的时间才能成功转换。积极支持uses a regex to detect times .你可以read the tests了解它支持的时间格式。看起来它支持 ISO 8601,但支持 Unix/POSIX/Epoch 时间戳。

我在创建 this issue against Rails 时在 Active Support 中获悉此功能.

一些历史:时间解析曾经是 Rails 中的默认行为,但后来为想要关闭它的人添加了 ActiveSupport.parse_json_times,然后它默认关闭,所以现在您必须选择加入。

关于ruby-on-rails - 如何使用 Ruby 将 JSON 时间字符串自动转换为时间对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49616614/

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