pretty_generate: don't apply object_nl / array_nl for empty containers

Fix: https://github.com/ruby/json/issues/437

Before:

```json
{
  "foo": {
  },
  "bar": [
  ]
}
```

After:

```json
{
  "foo": {},
  "bar": []
}
```
This commit is contained in:
Jean Boussier 2024-10-18 15:36:57 +02:00 committed by Hiroshi SHIBATA
parent 1d4708565f
commit bfdf02ea72
2 changed files with 21 additions and 0 deletions

View File

@ -681,6 +681,13 @@ static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_S
if (max_nesting != 0 && depth > max_nesting) {
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
}
if (RHASH_SIZE(obj) == 0) {
fbuffer_append(buffer, "{}", 2);
--state->depth;
return;
}
fbuffer_append_char(buffer, '{');
arg.buffer = buffer;
@ -709,6 +716,13 @@ static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_St
if (max_nesting != 0 && depth > max_nesting) {
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
}
if (RARRAY_LEN(obj) == 0) {
fbuffer_append(buffer, "[]", 2);
--state->depth;
return;
}
fbuffer_append_char(buffer, '[');
if (RB_UNLIKELY(state->array_nl)) fbuffer_append(buffer, state->array_nl, state->array_nl_len);
for(i = 0; i < RARRAY_LEN(obj); i++) {

View File

@ -90,10 +90,17 @@ EOT
def test_generate_pretty
json = pretty_generate({})
assert_equal('{}', json)
json = pretty_generate({1=>{}, 2=>[], 3=>4})
assert_equal(<<'EOT'.chomp, json)
{
"1": {},
"2": [],
"3": 4
}
EOT
json = pretty_generate(@hash)
# hashes aren't (insertion) ordered on every ruby implementation
# assert_equal(@json3, json)