Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

JSON.load_file: explictly load the file as UTF-8 #702

Merged
merged 1 commit into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Changes

* `JSON.load_file` explictly read the file as UTF-8.

### 2024-11-06 (2.8.1)

* Fix the java packages to include the extension.
Expand Down
9 changes: 5 additions & 4 deletions lib/json/common.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#frozen_string_literal: true
# frozen_string_literal: true

require 'json/version'

module JSON
Expand Down Expand Up @@ -230,8 +231,8 @@ def parse!(source, opts = {})
# parse(File.read(path), opts)
#
# See method #parse.
def load_file(filespec, opts = {})
parse(File.read(filespec), opts)
def load_file(filespec, opts = nil)
parse(File.read(filespec, encoding: Encoding::UTF_8), opts)
end

# :call-seq:
Expand All @@ -242,7 +243,7 @@ def load_file(filespec, opts = {})
#
# See method #parse!
def load_file!(filespec, opts = {})
parse!(File.read(filespec), opts)
parse!(File.read(filespec, encoding: Encoding::UTF_8), opts)
end

# :call-seq:
Expand Down
23 changes: 23 additions & 0 deletions test/json/json_common_interface_test.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# frozen_string_literal: true

require_relative 'test_helper'
require 'stringio'
require 'tempfile'
Expand Down Expand Up @@ -189,8 +190,30 @@ def test_load_file_with_option!
test_load_file_with_option_shared(:load_file!)
end

def test_load_file_with_bad_default_external_encoding
data = { "key" => "€" }
temp_file_containing(JSON.dump(data)) do |path|
loaded_data = with_external_encoding(Encoding::US_ASCII) do
JSON.load_file(path)
end
assert_equal data, loaded_data
end
end

private

def with_external_encoding(encoding)
verbose = $VERBOSE
$VERBOSE = nil
previous_encoding = Encoding.default_external
Encoding.default_external = encoding
yield
ensure
verbose = $VERBOSE
Encoding.default_external = previous_encoding
$VERBOSE = verbose
end

def test_load_shared(method_name)
temp_file_containing(@json) do |filespec|
assert_equal JSON.public_send(method_name, filespec), @hash
Expand Down