[英]Format array of date_time in hash during hash to json conversion
so I have a class whose hash representation looks like this.所以我有一个 class 其 hash 表示看起来像这样。
{"dateTime"=>[1484719381, 1484719381], "dateTime1"=>[1484719381, 1484719381]}
The dateTime here is is a unix formatted dateTime array. {"dateTime"=>[1484719381, 1484719381], "dateTime1"=>[1484719381, 1484719381]}
这里的dateTime是一个 unix 格式的 dateTime 数组。
I am trying to convert this hash to an equivalent of json_string for which I am using hash.to_json.我正在尝试将此 hash 转换为我正在使用 hash.to_json 的 json_string 的等效项。 Is there any way through which I can modify the format of date_time when calling to_json.
调用 to_json 时有什么方法可以修改 date_time 的格式。 The resulting json should look like this
生成的 json 应该如下所示
'{"dateTime1":["2017-01-18T06:03:01+00:00","2017-01-18T06:03:01+00:00"]}'
Basically I am looking for an implementation that can be called during hash.to_json.基本上我正在寻找可以在 hash.to_json 期间调用的实现。
You cannot make this part of Hash#to_json
without damaging that method dramatically because:您不能在不显着损坏该方法的情况下制作
Hash#to_json
的这一部分,因为:
#to_json
for multiple other classes#to_json
Integers
which is valid JSON and changing this would be awfulIntegers
JSON 并且改变它会很糟糕Time
object in Ruby so you need to string format it anywayTime
object 的字符串表示形式,因此无论如何您都需要对其进行字符串格式化Instead you would have to modify the Hash
values to represent in the desired fashion eg相反,您必须修改
Hash
值以以所需的方式表示,例如
h= {"dateTime"=>[1484719381, 14848723546], "dateTime1"=>[1484234567, 1484719381]}
h.transform_values do |v|
v.map do |int|
Time.at(int, in: '+00:00').strftime("%Y-%m-%dT%H:%M:%S%z")
end
end
#=> {"dateTime"=>[
# "2017-01-18T06:03:01+0000",
# "2440-07-15T05:25:46+0000"],
# "dateTime1"=>[
# "2017-01-12T15:22:47+0000",
# "2017-01-18T06:03:01+0000"]}
You could then call to_json
on the resulting object to get your desired result.然后,您可以在生成的 object 上调用
to_json
以获得您想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.