ruby / json

JSON implementation for Ruby
https://ruby.github.io/json
Other
673 stars 326 forks source link

Cannot convert time to json #573

Open BuonOmo opened 6 months ago

BuonOmo commented 6 months ago

Summary

The commit https://github.com/flori/json/commit/f65f2282 introduced a change in the to_json method that breaks Time.to_json.

Reproduction

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"
  gem "json_pure"
end

require "json/pure"

puts "ruby:      #{RUBY_VERSION}"
puts "json_pure: #{JSON::VERSION}"

time = Time.at(1_355_218_745).utc
time.to_json({})
Fetching gem metadata from https://rubygems.org/..
Resolving dependencies...
ruby:      3.2.3
json_pure: 2.7.1
../.rbenv/versions/3.2.3/lib/ruby/gems/3.2.0/gems/json_pure-2.7.1/lib/json/pure/generator.rb:320:in `to_json': undefined method `strict?' for {}:Hash (NoMethodError)

            if generator_state.strict?
                              ^^^^^^^^
    from pure_json.rb:14:in `<main>'

Fix

I think this would do the trick, but I'm not sur I understand why it is written that way today...

diff --git a/lib/json/pure/generator.rb b/lib/json/pure/generator.rb
index c85222c..d7f86a3 100644
--- a/lib/json/pure/generator.rb
+++ b/lib/json/pure/generator.rb
@@ -316,8 +316,8 @@ module JSON
           # Converts this object to a string (calling #to_s), converts
           # it to a JSON string, and returns the result. This is a fallback, if no
           # special method #to_json was defined for some object.
-          def to_json(generator_state)
-            if generator_state.strict?
+          def to_json(state = nil, *)
+            if State.from_state(state).strict?
               raise GeneratorError, "#{self.class} not allowed in JSON"
             else
               to_s.to_json