This module contains procs for serialization and deserialization of arbitrary Nim data structures. The serialization format uses JSON.
Restriction: For objects, their type is not serialized. This means essentially that it does not work if the object has some other runtime type than its compiletime type.
Example:
import std/marshal
type
A = object of RootObj
B = object of A
f: int
let a: ref A = new(B)
assert $$a[] == "{}" # not "{f: 0}"
# unmarshal
let c = to[B]("""{"f": 2}""")
assert typeof(c) is B
assert c.f == 2
# marshal
assert $$c == """{"f": 2}"""
Note: The to and $$ operations are available at compile-time! proc `$$`[T](x: sink T): string
Returns a string representation of x (serialization, marshalling).
Note: to serialize x to JSON use %x from the json module or jsonutils.toJson(x).
Example:
type
Foo = object
id: int
bar: string
let x = Foo(id: 1, bar: "baz")
## serialize:
let y = $$x
assert y == """{"id": 1, "bar": "baz"}""" Source Edit proc to[T](data: string): T
T (deserialization, unmarshalling). Example:
type
Foo = object
id: int
bar: string
let y = """{"id": 1, "bar": "baz"}"""
assert typeof(y) is string
## deserialize to type 'Foo':
let z = y.to[:Foo]
assert typeof(z) is Foo
assert z.id == 1
assert z.bar == "baz" Source Edit
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/marshal.html