Skip to content
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
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

### Unreleased

* Fix `JSON.generate` `strict: true` mode to also restrict hash keys.

### 2025-07-28 (2.13.2)

* Improve duplicate key warning and errors to include the key name and point to the right caller.
Expand Down
3 changes: 3 additions & 0 deletions ext/json/ext/generator/generator.c
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,9 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
key_to_s = rb_sym2str(key);
break;
default:
if (data->state->strict) {
raise_generator_error(key, "%"PRIsVALUE" not allowed in JSON", rb_funcall(key, i_to_s, 0));
}
key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
break;
}
Expand Down
3 changes: 3 additions & 0 deletions java/src/json/ext/Generator.java
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,9 @@ private static void processEntry(ThreadContext context, Session session, OutputS
} else if (keyClass == runtime.getSymbol()) {
keyStr = ((RubySymbol) key).id2name(context);
} else {
if (session.getState(context).strict()) {
throw Utils.buildGeneratorError(context, key, key + " not allowed in JSON").toThrowable();
}
keyStr = TypeConverter.convertToType(key, runtime.getString(), "to_s");
}

Expand Down
4 changes: 4 additions & 0 deletions lib/json/truffle_ruby/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,10 @@ def json_transform(state)
result << delim unless first
result << state.indent * depth if indent

if state.strict? && !(Symbol === key || String === key)
raise GeneratorError.new("#{key.class} not allowed in JSON", value)
end

key_str = key.to_s
if key_str.is_a?(String)
key_json = key_str.to_json(state)
Expand Down
12 changes: 12 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,18 @@ def test_json_generate_unsupported_types
assert_raise JSON::GeneratorError do
generate(Object.new, strict: true)
end

assert_raise JSON::GeneratorError do
generate([Object.new], strict: true)
end

assert_raise JSON::GeneratorError do
generate({ "key" => Object.new }, strict: true)
end

assert_raise JSON::GeneratorError do
generate({ Object.new => "value" }, strict: true)
end
end

def test_nesting
Expand Down
Loading