diff options
author | Jean Boussier <[email protected]> | 2024-10-18 15:36:57 +0200 |
---|---|---|
committer | Hiroshi SHIBATA <[email protected]> | 2024-10-26 18:44:15 +0900 |
commit | bfdf02ea7290d1d76e457ffbb15cfef5e64bf547 (patch) | |
tree | e24b355da11e28f8e2379dda0ca5a5ef39fd3879 /ext/json | |
parent | 1d4708565fead0291c5c54db60a196268d706aa6 (diff) |
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": []
}
```
Diffstat (limited to 'ext/json')
-rw-r--r-- | ext/json/generator/generator.c | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/ext/json/generator/generator.c b/ext/json/generator/generator.c index c35e86d9b8..fbfa2c724e 100644 --- a/ext/json/generator/generator.c +++ b/ext/json/generator/generator.c @@ -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++) { |