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