From d8778721279ccfd78f5a94ce1433b79ff150c6f3 Mon Sep 17 00:00:00 2001 From: Eric <5089238+emizzle@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:07:29 +1100 Subject: [PATCH] Add prettified option for toJson --- serde/json/serializer.nim | 6 +++++- tests/json/testSerialize.nim | 25 ++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/serde/json/serializer.nim b/serde/json/serializer.nim index 2b208e7..bbf86db 100644 --- a/serde/json/serializer.nim +++ b/serde/json/serializer.nim @@ -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 diff --git a/tests/json/testSerialize.nim b/tests/json/testSerialize.nim index a97c895..e28aa69 100644 --- a/tests/json/testSerialize.nim +++ b/tests/json/testSerialize.nim @@ -93,4 +93,27 @@ suite "json serialization - serialize": "myint": 1 }""".flatten - check $obj == expected \ No newline at end of file + 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 \ No newline at end of file