so I have a class whose hash representation looks like this.
{"dateTime"=>[1484719381, 1484719381], "dateTime1"=>[1484719381, 1484719381]}
The dateTime here is is a unix formatted dateTime array.
I am trying to convert this hash to an equivalent of json_string for which I am using hash.to_json. Is there any way through which I can modify the format of date_time when calling to_json. The resulting json should look like this
'{"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.
You cannot make this part of Hash#to_json
without damaging that method dramatically because:
#to_json
for multiple other classesIntegers
which is valid JSON and changing this would be awfulTime
object in Ruby so you need to string format it anywayInstead you would have to modify the Hash
values to represent in the desired fashion e.g.
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.