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

fix tuple conversion to JsonNode from % in pure/json.nim #24082

Closed
wants to merge 5 commits into from
Closed
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
6 changes: 4 additions & 2 deletions lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,9 @@ proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =

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

proc `%`*[T](elements: openArray[T]): JsonNode =
#Disallow tuples inside the array to avoid something like %{"test":"test1"} to get converted to [{"Field0":"test","Field1":"test1"}].
#See 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 @@ -390,7 +392,7 @@ proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) {.inline.} =
assert(obj.kind == JObject)
obj.fields[key] = val

proc `%`*[T: object](o: T): JsonNode =
proc `%`*[T: object | tuple](o: T): JsonNode =
## Construct JsonNode from tuples and objects.
result = newJObject()
for k, v in o.fieldPairs: result[k] = %v
Expand Down
14 changes: 13 additions & 1 deletion tests/stdlib/tjson.nim
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,19 @@ when not defined(js):
doAssert($ %*[] == "[]")
doAssert($ %*{} == "{}")

doAssert(not compiles(%{"error": "No messages"}))
#issue #24082 for more info
block testTuple:
let
testTupleNamed: tuple = (a1: 10, a2: "foo") #tuple with field names = named tuple
testTupleAnon: tuple = (10, "foo") #tuple without field names = anonymous tuple

doAssert $(% testTupleNamed) == """{"a1":10,"a2":"foo"}"""
doAssert $(% testTupleAnon) == """{"Field0":10,"Field1":"foo"}"""

doAssert $(%* testTupleNamed) == """{"a1":10,"a2":"foo"}"""
doAssert $(%* testTupleAnon) == """{"Field0":10,"Field1":"foo"}"""



# bug #9111
block:
Expand Down
Loading