Skip to content

Commit

Permalink
JSON::Pure fix strict mode
Browse files Browse the repository at this point in the history
Followup: #519
Fix: #584
  • Loading branch information
byroot committed May 9, 2024
1 parent 4f876a8 commit db37392
Show file tree
Hide file tree
Showing 2 changed files with 20 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? && !(!value || value == true || value.is_a?(Array) || value.is_a?(Integer) || value.is_a?(Float) || value.is_a?(String))
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? && !(!value || value == true || value.is_a?(Array) || value.is_a?(Integer) || value.is_a?(Float) || value.is_a?(String))
raise GeneratorError, "#{value.class} not allowed in JSON"
elsif value.respond_to?(:to_json)
result << value.to_json(state)
Expand Down
18 changes: 18 additions & 0 deletions tests/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,24 @@ 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}', dump({
"int" => 42,
"float" => 4.2,
"string" => "forty-two",
"true" => true,
"false" => false,
"nil" => nil,
}, 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 db37392

Please sign in to comment.