C# Serialized JSON Date to Ruby

c# serialized JSON date to ruby

You could parse out the milliseconds since the epoch, something like:

def parse_date(datestring)
seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0
return Time.at(seconds_since_epoch)
end

parse_date('/Date(1250170550493+0100)/')

You'd still need to handle the timezone info (the +0100 part), so this is a starting point.

How to format a date to JSON in Rails?

What about (ruby 1.9.x)?:

Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"

How to save data into JSON with Ruby and use it later?

You Need to Serialize to JSON First

You are currently writing native Ruby objects to your file, not JSON. To serialize an object to JSON, you need to call a method like #to_json on it after requiring the JSON module.

For example, using Ruby 3.0.3:

require 'json'

books = [{"Title"=>"My title", "Author"=>"My author"}]
File.open("books.json", "w") { |f| f.puts books.to_json }

will write the expected JSON object of [{"Title":"My title","Author":"My author"}] to your file and then close itself.

If you want, you can validate that this worked in Ruby, or at the command line with jq. As a command-line example:

jq . books.json 
[
{
"Title": "My title",
"Author": "My author"
}
]

There are certainly other ways to generate JSON objects in various formats for serialization, but that's the missing piece in your code. You have to convert your Ruby objects to JSON objects before writing them out to the file, or (in your case) you just end up writing the implicit #to_str value of the object instead.



Related Topics



Leave a reply



Submit