Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON::Pure fix strict mode #585

Merged
merged 1 commit into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/json/pure/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ def script_safe?
@script_safe
end

# Returns true, if forward slashes are escaped. Otherwise returns false.
# Returns true, if strict mode is enabled. Otherwise returns false.
# Strict mode only allow serializing JSON native types: Hash, Array,
# String, Integer, Float, true, false and nil.
def strict?
@strict
end
Expand Down Expand Up @@ -354,7 +356,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 +399,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
Loading