简体   繁体   English

hash 到 json 转换期间 hash 中的 date_time 格式数组

[英]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的这一部分,因为:

  • You would need to manipulate the #to_json for multiple other classes您需要为多个其他类操作#to_json
  • Those are Integers which is valid JSON and changing this would be awful这些是有效的Integers JSON 并且改变它会很糟糕
  • That is not the string representation of a Time object in Ruby so you need to string format it anyway这不是 Ruby 中Time 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM