Skip to content

Commit

Permalink
better approach via mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Jun 6, 2020
1 parent 7578ce5 commit 5ad78f5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 13 deletions.
7 changes: 2 additions & 5 deletions lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 9 additions & 7 deletions lib/pure/strtabs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion tests/stdlib/tjsonmacro.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 5ad78f5

Please sign in to comment.