Add prettified option for toJson

This commit is contained in:
Eric 2024-02-08 08:07:29 +11:00
parent 1a506be83a
commit d877872127
No known key found for this signature in database
2 changed files with 29 additions and 2 deletions

View File

@ -125,7 +125,11 @@ func `%`*[T: distinct](id: T): JsonNode =
type baseType = T.distinctBase
% baseType(id)
proc toJson*[T](item: T): string = $(%item)
proc toJson*[T](item: T, pretty = false): string =
if pretty:
(%item).pretty
else:
$(%item)
proc toJsnImpl(x: NimNode): NimNode =
case x.kind

View File

@ -93,4 +93,27 @@ suite "json serialization - serialize":
"myint": 1
}""".flatten
check $obj == expected
check $obj == expected
test "serializes to string with toJson":
type MyObj = object
mystring {.serialize.}: string
myint {.serialize.}: int
let obj = MyObj(mystring: "abc", myint: 1)
let expected = """{"mystring":"abc","myint":1}"""
check obj.toJson == expected
test "serializes prettied to string with toJson":
type MyObj = object
mystring {.serialize.}: string
myint {.serialize.}: int
let obj = MyObj(mystring: "abc", myint: 1)
let expected = """{
"mystring": "abc",
"myint": 1
}"""
check obj.toJson(pretty=true) == expected