forked from straight-shoota/crinja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_builder.cr
61 lines (54 loc) · 1.26 KB
/
json_builder.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
require "json"
struct Crinja::JsonBuilder
protected def self.new(io : IO, indent = 0)
builder = JSON::Builder.new(io)
builder.indent = indent
new(builder)
end
protected def initialize(@json : JSON::Builder)
end
private def dump(value)
case value
when Value
dump(value.raw)
when Callable, Callable::Proc
@json.string value.to_s
when Iterator, Array
@json.array do
value.each do |item|
dump(item)
end
end
when Hash
@json.object do
value.each do |key, item|
@json.field key.to_s do
dump(item)
end
end
end
when Crinja::Object
# FIXME: We need to detect if the class has a #to_json(JSON::Builder) method
# pending https://github.com/crystal-lang/crystal/issues/5695
@json.null
else
value.to_json(@json)
end
end
protected def to_json(value)
@json.start_document
dump(value)
@json.end_document
end
def self.to_json(value, indent = 0)
String.build do |io|
to_json(value, io, indent)
end
end
def self.to_json(io : IO, value, indent = 0)
new(io, indent).to_json(value)
end
def self.to_json(builder : JSON::Builder, value)
new(builder).to_json(value)
end
end