Skip to content

Commit 303bff7

Browse files
committed
Revert the removal of UTF-8 force encoding in JSON loading
I think the removal of the force encoding in #719 was a mistake. For example, my shell prompt includes multi-byte UTF-8 characters, and when `Spring::Client::Run#run_command` collects the environment variables using `ENV.to_hash`, the resulting JSON string becomes ASCII-8BIT. This causes issues when the `Spring::Application#serve` tries to load the JSON string and passes it to `JSON.load`. Since `OkJson` expects UTF-8 encoded strings, it raises an error when it encounters the ASCII-8BIT string. I've added a test case that replicates this issue to ensure that the encoding is handled correctly. The test case creates a JSON string with multi-byte UTF-8 characters as an ASCII-8BIT string and verifies that it can be loaded without raising an error.
1 parent 1821287 commit 303bff7

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

lib/spring/json.rb

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
module Spring
1414
module JSON
1515
def self.load(string)
16+
string = string.dup.force_encoding("utf-8") unless string.encoding == Encoding::UTF_8
1617
OkJson.decode(string)
1718
end
1819

test/unit/json_test.rb

+6-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ class JsonTest < ActiveSupport::TestCase
66
assert_equal({"unicode_example"=>"©"}, Spring::JSON.load('{"unicode_example": "\u00A9"}'))
77
end
88

9+
test 'can decode binary strings with valid UTF8 characters' do
10+
string = "{\"PS1\":\"\xEF\x90\x98 main \xEE\x9E\x91 v3.4.2\"}".b
11+
assert_equal({"PS1"=>" main  v3.4.2"}, Spring::JSON.load(string))
12+
end
13+
914
test 'can encode' do
1015
assert_equal('{}', Spring::JSON.dump({}))
11-
end
16+
end
1217
end

0 commit comments

Comments
 (0)