summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorOscar NihlgÄrd <oscarnihlgard@gmail.com>2019-02-09 22:34:35 +0100
committerAndreas Rumpf <rumpf_a@web.de>2019-02-13 23:30:14 +0100
commit779c51c29b7d78ec57ac2b50d2a1fe01056dbf5c (patch)
tree8596c6e2fc7aa1f1aaac599f6433ff2aef1e5ec6
parentd83520ec8f2e9b61c59930d7353ff621ef2ad3ec (diff)
downloadNim-779c51c29b7d78ec57ac2b50d2a1fe01056dbf5c.tar.gz
Implement `json.%` for tables and options
-rw-r--r--lib/pure/json.nim12
1 files changed, 11 insertions, 1 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index 176da1d9d..e387c516b 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -143,7 +143,7 @@ runnableExamples:
 
 import
   hashes, tables, strutils, lexbase, streams, unicode, macros, parsejson,
-  typetraits
+  typetraits, options
 
 export
   tables.`$`
@@ -344,6 +344,16 @@ proc `%`*[T](elements: openArray[T]): JsonNode =
   result = newJArray()
   for elem in elements: result.add(%elem)
 
+proc `%`*[T](table: Table[string, T]|OrderedTable[string, T]): JsonNode =
+  ## Generic constructor for JSON data. Creates a new ``JObject JsonNode``.
+  result = newJObject()
+  for k, v in table: result[k] = %v
+
+proc `%`*[T](opt: Option[T]): JsonNode =
+  ## Generic constructor for JSON data. Creates a new ``JNull JsonNode``
+  ## if ``opt`` is empty, otherwise it delegates to the underlying value.
+  if opt.isSome: %opt.get else: newJNull()
+
 when false:
   # For 'consistency' we could do this, but that only pushes people further
   # into that evil comfort zone where they can use Nim without understanding it