diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 3d68ae5cf655..e5f1e55e0464 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -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) @@ -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 diff --git a/tests/stdlib/tjson.nim b/tests/stdlib/tjson.nim index 691bedeaabe7..590cd72cd8c8 100644 --- a/tests/stdlib/tjson.nim +++ b/tests/stdlib/tjson.nim @@ -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: