Improved performance of "$" on jsonnode

This commit is contained in:
Erik O'Leary 2015-05-15 22:12:31 -05:00
commit 911c5d45ec

View file

@ -949,10 +949,50 @@ proc pretty*(node: JsonNode, indent = 2): string =
result = ""
toPretty(result, node, indent)
proc toUgly*(result: var string, node: JsonNode) =
## Converts `node` to its JSON Representation, without
## regard for human redability.
var comma = false
case node.kind:
of JArray:
result.add "["
for child in node.elems:
if comma: result.add ","
else: comma = true
result.toUgly child
result.add "]"
of JObject:
result.add "{"
for key, value in items(node.fields):
if comma: result.add ","
else: comma = true
result.add "\""
result.add key.escapeJson()
result.add "\":"
result.toUgly value
result.add "}"
of JString:
result.add "\""
result.add node.str.escapeJson()
result.add "\""
of JInt:
result.add($node.num)
of JFloat:
result.add($node.fnum)
of JBool:
result.add(if node.bval: "true" else: "false")
of JNull:
result.add "null"
proc toUgly*(node: JsonNode): string =
## Converts `node` to its JSON Representation on one line.
result = newStringOfCap(node.len shl 1)
toUgly(result, node)
proc `$`*(node: JsonNode): string =
## Converts `node` to its JSON Representation on one line.
result = ""
toPretty(result, node, 0, false)
result = newStringOfCap(node.len shl 1)
toUgly(result, node)
iterator items*(node: JsonNode): JsonNode =
## Iterator for the items of `node`. `node` has to be a JArray.