File tree Expand file tree Collapse file tree 3 files changed +30
-4
lines changed Expand file tree Collapse file tree 3 files changed +30
-4
lines changed Original file line number Diff line number Diff line change 1
1
# Changes
2
2
3
+ * ` JSON.load_file ` explictly read the file as UTF-8.
4
+
3
5
### 2024-11-06 (2.8.1)
4
6
5
7
* Fix the java packages to include the extension.
Original file line number Diff line number Diff line change 1
- #frozen_string_literal: true
1
+ # frozen_string_literal: true
2
+
2
3
require 'json/version'
3
4
4
5
module JSON
@@ -230,8 +231,8 @@ def parse!(source, opts = {})
230
231
# parse(File.read(path), opts)
231
232
#
232
233
# See method #parse.
233
- def load_file ( filespec , opts = { } )
234
- parse ( File . read ( filespec ) , opts )
234
+ def load_file ( filespec , opts = nil )
235
+ parse ( File . read ( filespec , encoding : Encoding :: UTF_8 ) , opts )
235
236
end
236
237
237
238
# :call-seq:
@@ -242,7 +243,7 @@ def load_file(filespec, opts = {})
242
243
#
243
244
# See method #parse!
244
245
def load_file! ( filespec , opts = { } )
245
- parse! ( File . read ( filespec ) , opts )
246
+ parse! ( File . read ( filespec , encoding : Encoding :: UTF_8 ) , opts )
246
247
end
247
248
248
249
# :call-seq:
Original file line number Diff line number Diff line change 1
1
# frozen_string_literal: true
2
+
2
3
require_relative 'test_helper'
3
4
require 'stringio'
4
5
require 'tempfile'
@@ -189,8 +190,30 @@ def test_load_file_with_option!
189
190
test_load_file_with_option_shared ( :load_file! )
190
191
end
191
192
193
+ def test_load_file_with_bad_default_external_encoding
194
+ data = { "key" => "€" }
195
+ temp_file_containing ( JSON . dump ( data ) ) do |path |
196
+ loaded_data = with_external_encoding ( Encoding ::US_ASCII ) do
197
+ JSON . load_file ( path )
198
+ end
199
+ assert_equal data , loaded_data
200
+ end
201
+ end
202
+
192
203
private
193
204
205
+ def with_external_encoding ( encoding )
206
+ verbose = $VERBOSE
207
+ $VERBOSE = nil
208
+ previous_encoding = Encoding . default_external
209
+ Encoding . default_external = encoding
210
+ yield
211
+ ensure
212
+ verbose = $VERBOSE
213
+ Encoding . default_external = previous_encoding
214
+ $VERBOSE = verbose
215
+ end
216
+
194
217
def test_load_shared ( method_name )
195
218
temp_file_containing ( @json ) do |filespec |
196
219
assert_equal JSON . public_send ( method_name , filespec ) , @hash
You can’t perform that action at this time.
0 commit comments