jjson: added the %* macro inspired from json.nim
This commit is contained in:
parent
b8c9ff45fe
commit
b5fc4de010
1 changed files with 34 additions and 0 deletions
|
|
@ -19,9 +19,12 @@ proc newJsonNode*(fields: varargs[(cstring, JsonNode)]): JsonNode =
|
|||
proc newJObject*(): JsonNode =
|
||||
result = JsonNode()
|
||||
|
||||
proc newJArray*(elements: varargs[JsonNode]): JsonNode {.importcpp: "#".}
|
||||
|
||||
proc newJNull*(): JsonNode = nil
|
||||
|
||||
template `%`*(x: typed): JsonNode = cast[JsonNode](x)
|
||||
template `%`*(x: string): JsonNode = cast[JsonNode](cstring x)
|
||||
|
||||
proc getNum*(x: JsonNode): int {.importcpp: "#".}
|
||||
|
||||
|
|
@ -31,3 +34,34 @@ proc getFNum*(x: JsonNode): cstring {.importcpp: "#".}
|
|||
|
||||
iterator items*(x: JsonNode): JsonNode =
|
||||
for i in 0..<len(x): yield x[i]
|
||||
|
||||
import macros
|
||||
|
||||
proc toJson(x: NimNode): NimNode {.compiletime.} =
|
||||
case x.kind
|
||||
of nnkBracket:
|
||||
result = newCall(bindSym"newJArray")
|
||||
for i in 0 ..< x.len:
|
||||
result.add(toJson(x[i]))
|
||||
of nnkTableConstr:
|
||||
result = newCall(bindSym"newJsonNode")
|
||||
for i in 0 ..< x.len:
|
||||
x[i].expectKind nnkExprColonExpr
|
||||
let key = x[i][0]
|
||||
let a = if x[i].kind in {nnkIdent, nnkSym, nnkAccQuoted}:
|
||||
newLit($key)
|
||||
else:
|
||||
key
|
||||
result.add newTree(nnkPar, newCall(bindSym"cstring", a), toJson(x[i][1]))
|
||||
of nnkCurly:
|
||||
x.expectLen(0)
|
||||
result = newCall(bindSym"newJObject")
|
||||
of nnkNilLit:
|
||||
result = newCall(bindSym"newJNull")
|
||||
else:
|
||||
result = newCall(bindSym"%", x)
|
||||
|
||||
macro `%*`*(x: untyped): untyped =
|
||||
## Convert an expression to a JsonNode directly, without having to specify
|
||||
## `%` for every element.
|
||||
result = toJson(x)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue