Skip to content

Commit bfdf02e

Browse files
byroothsbt
authored andcommitted
pretty_generate: don't apply object_nl / array_nl for empty containers
Fix: ruby/json#437 Before: ```json { "foo": { }, "bar": [ ] } ``` After: ```json { "foo": {}, "bar": [] } ```
1 parent 1d47085 commit bfdf02e

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

ext/json/generator/generator.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,13 @@ static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_S
681681
if (max_nesting != 0 && depth > max_nesting) {
682682
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
683683
}
684+
685+
if (RHASH_SIZE(obj) == 0) {
686+
fbuffer_append(buffer, "{}", 2);
687+
--state->depth;
688+
return;
689+
}
690+
684691
fbuffer_append_char(buffer, '{');
685692

686693
arg.buffer = buffer;
@@ -709,6 +716,13 @@ static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_St
709716
if (max_nesting != 0 && depth > max_nesting) {
710717
rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
711718
}
719+
720+
if (RARRAY_LEN(obj) == 0) {
721+
fbuffer_append(buffer, "[]", 2);
722+
--state->depth;
723+
return;
724+
}
725+
712726
fbuffer_append_char(buffer, '[');
713727
if (RB_UNLIKELY(state->array_nl)) fbuffer_append(buffer, state->array_nl, state->array_nl_len);
714728
for(i = 0; i < RARRAY_LEN(obj); i++) {

test/json/json_generator_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,17 @@ def test_dump_strict
9090

9191
def test_generate_pretty
9292
json = pretty_generate({})
93+
assert_equal('{}', json)
94+
95+
json = pretty_generate({1=>{}, 2=>[], 3=>4})
9396
assert_equal(<<'EOT'.chomp, json)
9497
{
98+
"1": {},
99+
"2": [],
100+
"3": 4
95101
}
96102
EOT
103+
97104
json = pretty_generate(@hash)
98105
# hashes aren't (insertion) ordered on every ruby implementation
99106
# assert_equal(@json3, json)

0 commit comments

Comments
 (0)