Skip to content

Commit

Permalink
Fix an issue with generate_pretty and empty objects in the Ruby and J…
Browse files Browse the repository at this point in the history
…ava implementations
  • Loading branch information
chrisseaton committed Oct 7, 2020
1 parent 07c3404 commit f5916bd
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
5 changes: 4 additions & 1 deletion java/src/json/ext/Generator.java
Expand Up @@ -334,6 +334,8 @@ void generate(final Session session, RubyHash object,

buffer.append((byte)'{');
buffer.append(objectNl);

final int[] count = new int[]{0};
object.visitAll(new RubyHash.Visitor() {
private boolean firstPair = true;

Expand All @@ -357,10 +359,11 @@ public void visit(IRubyObject key, IRubyObject value) {
Handler<IRubyObject> valueHandler = getHandlerFor(runtime, value);
valueHandler.generate(session, value, buffer);
session.infectBy(value);
count[0]++;
}
});
state.decreaseDepth();
if (objectNl.length() != 0) {
if (count[0] > 0 && objectNl.length() != 0) {
buffer.append(objectNl);
buffer.append(Utils.repeat(state.getIndent(), state.getDepth()));
}
Expand Down
8 changes: 6 additions & 2 deletions lib/json/pure/generator.rb
Expand Up @@ -317,6 +317,7 @@ def json_transform(state)
depth = state.depth += 1
first = true
indent = !state.object_nl.empty?
count = 0
each { |key,value|
result << delim unless first
result << state.indent * depth if indent
Expand All @@ -330,10 +331,13 @@ def json_transform(state)
result << %{"#{String(value)}"}
end
first = false
count += 1
}
depth = state.depth -= 1
result << state.object_nl
result << state.indent * depth if indent
unless count.zero?
result << state.object_nl
result << state.indent * depth if indent
end
result << '}'
result
end
Expand Down
5 changes: 5 additions & 0 deletions tests/json_generator_test.rb
Expand Up @@ -92,6 +92,11 @@ def test_generate
end

def test_generate_pretty
json = pretty_generate({})
assert_equal(<<'EOT'.chomp, json)
{
}
EOT
json = pretty_generate(@hash)
# hashes aren't (insertion) ordered on every ruby implementation
# assert_equal(@json3, json)
Expand Down

0 comments on commit f5916bd

Please sign in to comment.