Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow tuples to be converted to JsonNode by % in json.nim as discussed in #24082 . #24089

Open
wants to merge 6 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ type

const DepthLimit = 1000

proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}

proc newJString*(s: string): JsonNode =
## Creates a new `JString JsonNode`.
result = JsonNode(kind: JString, str: s)
Expand Down Expand Up @@ -363,7 +365,8 @@ proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =

template `%`*(j: JsonNode): JsonNode = j

proc `%`*[T](elements: openArray[T]): JsonNode =
#tuples must not be allowed - issue #24082
proc `%`*[T: not tuple](elements: openArray[T]): JsonNode =
## Generic constructor for JSON data. Creates a new `JArray JsonNode`
result = newJArray()
for elem in elements: result.add(%elem)
Expand Down Expand Up @@ -396,8 +399,21 @@ proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) {.inline.} =
assert(obj.kind == JObject)
obj.fields[key] = val

#Bug #16321 - create seperate proc for tuple and object
proc `%`*[T: tuple](o: T): JsonNode =
## Construct JsonNode from tuples.
##
## If passed an anonymous tuple, creates `JArray JsonNode`,
## otherwise (named tuples) `JObject JsonNode`.
when T is isNamedTuple(T):
result = newJObject()
for k, v in o.fieldPairs: result[k] = %v
else:
result = newJArray()
for v in o.fields: result.add(%v)

proc `%`*[T: object](o: T): JsonNode =
## Construct JsonNode from tuples and objects.
## Construct JsonNode from objects.
result = newJObject()
for k, v in o.fieldPairs: result[k] = %v

Expand Down
8 changes: 8 additions & 0 deletions tests/stdlib/tjson.nim
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,14 @@ doAssert($ %*{} == "{}")

doAssert(not compiles(%{"error": "No messages"}))

# issue #24082
block test_tuple:
doAssert $(%(a1: 10, a2: "foo")) == """{"a1":10,"a2":"foo"}"""
doAssert $(%(10, "foo")) == """[10,"foo"]"""

doAssert $(%* (a1: 10, a2: "foo")) == """{"a1":10,"a2":"foo"}"""
doAssert $(%* (10, "foo")) == """[10,"foo"]"""

# bug #9111
block:
type
Expand Down
Loading