Skip to content

Commit

Permalink
Showing 2 changed files with 29 additions and 21 deletions.
8 changes: 8 additions & 0 deletions spec/std/json/serialization_spec.cr
Original file line number Diff line number Diff line change
@@ -262,6 +262,14 @@ describe "JSON serialization" do
it "does for empty Hash" do
({} of Nil => Nil).to_pretty_json.should eq(%({}))
end

it "does for Array with indent" do
[1, 2, 3].to_pretty_json(indent: " ").should eq("[\n 1,\n 2,\n 3\n]")
end

it "does for nested Hash with indent" do
{"foo" => {"bar" => 1}}.to_pretty_json(indent: " ").should eq(%({\n "foo": {\n "bar": 1\n }\n}))
end
end

it "generates an array with JSON::Builder" do
42 changes: 21 additions & 21 deletions src/json/to_json.cr
Original file line number Diff line number Diff line change
@@ -5,20 +5,20 @@ class Object
end
end

def to_pretty_json
def to_pretty_json(indent : String = " ")
String.build do |str|
to_pretty_json str
to_pretty_json str, indent: indent
end
end

def to_pretty_json(io : IO)
to_json JSON::PrettyWriter.new(io)
def to_pretty_json(io : IO, indent : String = " ")
to_json JSON::PrettyWriter.new(io, indent: indent)
end
end

# Handly struct to write JSON objects
struct JSON::ObjectBuilder(T)
def initialize(@io : T, @indent = 0)
def initialize(@io : T, @indent : String = " ", @indent_level : Int32 = 0)
@count = 0
end

@@ -32,20 +32,20 @@ struct JSON::ObjectBuilder(T)
def field(name)
if @count > 0
@io << ","
@io << '\n' if @indent > 0
@io << '\n' if @indent_level > 0
end
@indent.times { @io << " " }
@indent_level.times { @io << @indent }
name.to_s.to_json(@io)
@io << ":"
@io << " " if @indent > 0
@io << " " if @indent_level > 0
yield
@count += 1
end
end

# Handly struct to write JSON arrays
struct JSON::ArrayBuilder(T)
def initialize(@io : T, @indent = 0)
def initialize(@io : T, @indent : String = " ", @indent_level : Int32 = 0)
@count = 0
end

@@ -64,9 +64,9 @@ struct JSON::ArrayBuilder(T)
def push
if @count > 0
@io << ","
@io << '\n' if @indent > 0
@io << '\n' if @indent_level > 0
end
@indent.times { @io << " " }
@indent_level.times { @io << @indent }
yield
@count += 1
end
@@ -116,30 +116,30 @@ end
class JSON::PrettyWriter
include IO

def initialize(@io : IO)
@indent = 0
def initialize(@io : IO, @indent : String)
@indent_level = 0
end

delegate read, to: @io
delegate write, to: @io

def json_object
self << "{\n"
@indent += 1
yield JSON::ObjectBuilder.new(self, @indent)
@indent -= 1
@indent_level += 1
yield JSON::ObjectBuilder.new(self, @indent, @indent_level)
@indent_level -= 1
self << '\n'
@indent.times { @io << " " }
@indent_level.times { @io << @indent }
self << "}"
end

def json_array
self << "[\n"
@indent += 1
yield JSON::ArrayBuilder.new(self, @indent)
@indent -= 1
@indent_level += 1
yield JSON::ArrayBuilder.new(self, @indent, @indent_level)
@indent_level -= 1
self << '\n'
@indent.times { @io << " " }
@indent_level.times { @io << @indent }
self << ']'
end
end

0 comments on commit db7c8f8

Please sign in to comment.