diff --git a/lib/pure/json.nim b/lib/pure/json.nim index f5e2d64ea759..c420ee6ca128 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -1269,11 +1269,8 @@ proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".} proc toJson*[T](a: T): JsonNode {.since: (1,3,5).} = ## like `%` but allows custom serialization hook if `serialize(a: T)` is in scope - when compiles(serialize(a)): - proc funAdd(t: JsonNode, key: string, val: string) = t[key] = %val - proc funAdd2(t: JsonNode, key: string, val: JsonNode) = t[key] = val - proc funObj(): JsonNode = newJObject() - result = serialize(a, funObj, funAdd, funAdd2) + when compiles(toJsonHook(a)): + result = toJsonHook(a) elif T is object | tuple: const isNamed = T is object or isNamedTuple(T) when isNamed: diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index 7e814a585c33..cc1df7b0cd12 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -419,14 +419,16 @@ proc `%`*(f: string, t: StringTableRef, flags: set[FormatFlag] = {}): string {. add(result, f[i]) inc(i) -proc serialize*(a: StringTableRef) = discard -proc serialize*[T1, T2, T3](a: StringTableRef, funObj: T1, funAdd: T2, funAdd2: T3): auto = +proc toJsonHook*[](a: StringTableRef): auto = ## allows a custom serializer (eg json) to serialize this as we want. - result = funObj() - funAdd(result, "mode", $a.mode) - let t = funObj() - for k,v in a: funAdd(t, k, v) - funAdd2(result, "table", t) + mixin newJObject + mixin toJson + result = newJObject() + result["mode"] = toJson($a.mode) + let t = newJObject() + for k,v in a: + t[k] = toJson(v) + result["table"] = t when isMainModule: var x = {"k": "v", "11": "22", "565": "67"}.newStringTable diff --git a/tests/stdlib/tjsonmacro.nim b/tests/stdlib/tjsonmacro.nim index a5a1b53a2320..e2ac65784324 100644 --- a/tests/stdlib/tjsonmacro.nim +++ b/tests/stdlib/tjsonmacro.nim @@ -642,7 +642,7 @@ import strtabs proc testCustom()= var t = {"name": "John", "city": "Monaco"}.newStringTable let s = toJson(t) - doAssert $s == """{"mode":"modeCaseSensitive","table":{"city":"Monaco","name":"John"}}""" + doAssert $s == """{"mode":"modeCaseSensitive","table":{"city":"Monaco","name":"John"}}""", $s proc testToJson() = var t = {"z": "Z", "y": "Y"}.newStringTable