@@ -140,20 +140,17 @@ def stringify(jsonified)
140140 end
141141 end
142142
143- if defined? ( ::JSON ::Coder )
143+ # ruby/json 2.14.x yields non-String keys but doesn't let us know it's a key
144+ if defined? ( ::JSON ::Coder ) && !::JSON ::VERSION . start_with? ( "2.14." )
144145 class JSONGemCoderEncoder # :nodoc:
145146 JSON_NATIVE_TYPES = [ Hash , Array , Float , String , Symbol , Integer , NilClass , TrueClass , FalseClass , ::JSON ::Fragment ] . freeze
146- CODER = ::JSON ::Coder . new do |value |
147+ CODER = ::JSON ::Coder . new do |value , is_key |
147148 json_value = value . as_json
149+ # Keep compatibility by calling to_s on non-String keys
150+ next json_value . to_s if is_key
148151 # Handle objects returning self from as_json
149152 if json_value . equal? ( value )
150- if JSON_NATIVE_TYPES . include? ( json_value . class )
151- # If the callback is invoked for a native type,
152- # it means it is hash keys, e.g. { 1 => true }
153- next json_value . to_s
154- else
155- next ::JSON ::Fragment . new ( ::JSON . generate ( json_value ) )
156- end
153+ next ::JSON ::Fragment . new ( ::JSON . generate ( json_value ) )
157154 end
158155 # Handle objects not returning JSON-native types from as_json
159156 count = 5
@@ -222,7 +219,7 @@ def encode_without_options(value) # :nodoc:
222219 self . use_standard_json_time_format = true
223220 self . escape_html_entities_in_json = true
224221 self . json_encoder =
225- if defined? ( :: JSON :: Coder )
222+ if defined? ( JSONGemCoderEncoder )
226223 JSONGemCoderEncoder
227224 else
228225 JSONGemEncoder
0 commit comments