Skip to content

Commit 3652866

Browse files
committed
JSON::Pure fix strict mode
Followup: #519 Fix: #584
1 parent 4f876a8 commit 3652866

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

lib/json/pure/generator.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,9 @@ def script_safe?
219219
@script_safe
220220
end
221221

222-
# Returns true, if forward slashes are escaped. Otherwise returns false.
222+
# Returns true, if strict mode is enabled. Otherwise returns false.
223+
# Strict mode only allow serializing JSON native types: Hash, Array,
224+
# String, Integer, Float, true, false and nil.
223225
def strict?
224226
@strict
225227
end
@@ -354,7 +356,7 @@ def json_transform(state)
354356
result << delim unless first
355357
result << state.indent * depth if indent
356358
result = "#{result}#{key.to_s.to_json(state)}#{state.space_before}:#{state.space}"
357-
if state.strict?
359+
if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value)
358360
raise GeneratorError, "#{value.class} not allowed in JSON"
359361
elsif value.respond_to?(:to_json)
360362
result << value.to_json(state)
@@ -397,7 +399,7 @@ def json_transform(state)
397399
each { |value|
398400
result << delim unless first
399401
result << state.indent * depth if indent
400-
if state.strict?
402+
if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value)
401403
raise GeneratorError, "#{value.class} not allowed in JSON"
402404
elsif value.respond_to?(:to_json)
403405
result << value.to_json(state)

tests/json_generator_test.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,25 @@ def test_dump_unenclosed_hash
6767

6868
def test_dump_strict
6969
assert_equal '{}', dump({}, strict: true)
70+
71+
assert_equal '{"array":[42,4.2,"forty-two",true,false,null]}', dump({
72+
"array" => [42, 4.2, "forty-two", true, false, nil]
73+
}, strict: true)
74+
75+
assert_equal '{"int":42,"float":4.2,"string":"forty-two","true":true,"false":false,"nil":null,"hash":{}}', dump({
76+
"int" => 42,
77+
"float" => 4.2,
78+
"string" => "forty-two",
79+
"true" => true,
80+
"false" => false,
81+
"nil" => nil,
82+
"hash" => {},
83+
}, strict: true)
84+
85+
assert_equal '[]', dump([], strict: true)
86+
87+
assert_equal '42', dump(42, strict: true)
88+
assert_equal 'true', dump(true, strict: true)
7089
end
7190

7291
def test_generate_pretty

0 commit comments

Comments
 (0)