From 181c834a932ac98bc4451c6f0110cf9816b9808b Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Tue, 5 Apr 2016 22:55:00 +0300 Subject: [PATCH] Added json.getOrDefault along with {singleKey} tr optimization. --- lib/pure/json.nim | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 5be0986640..b9da8a0dd0 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -858,6 +858,14 @@ proc `{}`*(node: JsonNode, keys: varargs[string]): JsonNode = return nil result = result.fields.getOrDefault(key) +proc getOrDefault*(node: JsonNode, key: string): JsonNode = + ## Gets a field from a `node`. If `node` is nil or not an object or + ## value at `key` does not exist, returns nil + if not isNil(node) and node.kind == JObject: + result = node.fields.getOrDefault(key) + +template simpleGetOrDefault*{`{}`(node, [key])}(node: JsonNode, key: string): JsonNode = node.getOrDefault(key) + proc `{}=`*(node: JsonNode, keys: varargs[string], value: JsonNode) = ## Traverses the node and tries to set the value at the given location ## to ``value``. If any of the keys are missing, they are added.