Skip to content

Commit fa43c6f

Browse files
authored
Merge pull request #602 from byroot/pure-string-to-json
JSONPure: String#to_json should raise on invalid encoding
2 parents 2ebfc07 + f69f21e commit fa43c6f

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

lib/json/pure/generator.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,9 @@ module String
450450
def to_json(state = nil, *args)
451451
state = State.from_state(state)
452452
if encoding == ::Encoding::UTF_8
453+
unless valid_encoding?
454+
raise GeneratorError, "source sequence is illegal/malformed utf-8"
455+
end
453456
string = self
454457
else
455458
string = encode(::Encoding::UTF_8)

tests/json_generator_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,13 @@ def to_s; self; end
438438
end
439439
end
440440

441+
def test_invalid_encoding_string
442+
error = assert_raise(JSON::GeneratorError) do
443+
"\x82\xAC\xEF".to_json
444+
end
445+
assert_includes error.message, "source sequence is illegal/malformed utf-8"
446+
end
447+
441448
if defined?(JSON::Ext::Generator) and RUBY_PLATFORM != "java"
442449
def test_string_ext_included_calls_super
443450
included = false

0 commit comments

Comments
 (0)