Skip to content

Commit

Permalink
JSON::Pure fix strict mode
Browse files Browse the repository at this point in the history
Followup: flori#519
Fix: flori#584
  • Loading branch information
byroot committed May 9, 2024
1 parent 4f876a8 commit 937900c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/json/pure/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ def json_transform(state)
result << delim unless first
result << state.indent * depth if indent
result = "#{result}#{key.to_s.to_json(state)}#{state.space_before}:#{state.space}"
if state.strict?
if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value)
raise GeneratorError, "#{value.class} not allowed in JSON"
elsif value.respond_to?(:to_json)
result << value.to_json(state)
Expand Down Expand Up @@ -397,7 +397,7 @@ def json_transform(state)
each { |value|
result << delim unless first
result << state.indent * depth if indent
if state.strict?
if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value)
raise GeneratorError, "#{value.class} not allowed in JSON"
elsif value.respond_to?(:to_json)
result << value.to_json(state)
Expand Down
19 changes: 19 additions & 0 deletions tests/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ def test_dump_unenclosed_hash

def test_dump_strict
assert_equal '{}', dump({}, strict: true)

assert_equal '{"array":[42,4.2,"forty-two",true,false,null]}', dump({
"array" => [42, 4.2, "forty-two", true, false, nil]
}, strict: true)

assert_equal '{"int":42,"float":4.2,"string":"forty-two","true":true,"false":false,"nil":null,"hash":{}}', dump({
"int" => 42,
"float" => 4.2,
"string" => "forty-two",
"true" => true,
"false" => false,
"nil" => nil,
"hash" => {},
}, strict: true)

assert_equal '[]', dump([], strict: true)

assert_equal '42', dump(42, strict: true)
assert_equal 'true', dump(true, strict: true)
end

def test_generate_pretty
Expand Down

0 comments on commit 937900c

Please sign in to comment.