diff options
author | Timothee Cour <timothee.cour2@gmail.com> | 2019-01-16 01:16:14 -0800 |
---|---|---|
committer | Andreas Rumpf <rumpf_a@web.de> | 2019-01-16 10:16:14 +0100 |
commit | b8454327c52faa82632cc90dd8fa326efbb38565 (patch) | |
tree | 0590168b046180fb386b5d73a8166da18fde790b | |
parent | 384e517f09cf63cde136123b163c5c021c992877 (diff) | |
download | Nim-b8454327c52faa82632cc90dd8fa326efbb38565.tar.gz |
json: support tuple (#10010)
-rw-r--r-- | lib/pure/json.nim | 17 | ||||
-rw-r--r-- | tests/stdlib/tjsonmacro.nim | 4 |
2 files changed, 20 insertions, 1 deletions
diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 010dd8f70..02fa6dc67 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -142,7 +142,8 @@ runnableExamples: doAssert $(%* Foo()) == """{"a1":0,"a2":0,"a0":0,"a3":0,"a4":0}""" import - hashes, tables, strutils, lexbase, streams, unicode, macros, parsejson + hashes, tables, strutils, lexbase, streams, unicode, macros, parsejson, + typetraits export tables.`$` @@ -356,6 +357,20 @@ when false: assert false notin elements, "usage error: only empty sets allowed" assert true notin elements, "usage error: only empty sets allowed" +#[ +Note: could use simply: +proc `%`*(o: object|tuple): JsonNode +but blocked by https://github.com/nim-lang/Nim/issues/10019 +]# +proc `%`*(o: tuple): JsonNode = + ## Generic constructor for JSON data. Creates a new `JObject JsonNode` + when isNamedTuple(type(o)): + result = newJObject() + for k, v in o.fieldPairs: result[k] = %v + else: + result = newJArray() + for a in o.fields: result.add(%a) + proc `%`*(o: object): JsonNode = ## Generic constructor for JSON data. Creates a new `JObject JsonNode` result = newJObject() diff --git a/tests/stdlib/tjsonmacro.nim b/tests/stdlib/tjsonmacro.nim index 33332447b..2e95b4833 100644 --- a/tests/stdlib/tjsonmacro.nim +++ b/tests/stdlib/tjsonmacro.nim @@ -516,3 +516,7 @@ when true: var w = u.to(MyDistRef) doAssert v.name == "smith" doAssert MyRef(w).name == "smith" + + block test_tuple: + doAssert $(%* (a1: 10, a2: "foo")) == """{"a1":10,"a2":"foo"}""" + doAssert $(%* (10, "foo")) == """[10,"foo"]""" |