On this page
marshal
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.
Basic usage
type
A = object of RootObj
B = object of A
f: int
var
a: ref A
b: ref B
new(b)
a = b
echo($$a[]) # produces "{}", not "{f: 0}"
# unmarshal
let c = to[B]("""{"f": 2}""")
assert typeof(c) is B
assert c.f == 2
# marshal
let s = $$c
assert s == """{"f": 2}"""
Note: The to
and $$
operations are available at compile-time!
See also
Imports
Procs
-
proc load[T](s: Stream; data: var T)
-
Loads
data
from the streams
. RaisesIOError
in case of an error.Example:
Source Editimport marshal, streams var s = newStringStream("[1, 3, 5]") var a: array[3, int] load(s, a) assert a == [1, 3, 5]
-
proc store[T](s: Stream; data: T)
-
Stores
data
into the streams
. RaisesIOError
in case of an error.Example:
Source Editimport marshal, streams var s = newStringStream("") var a = [1, 3, 5] store(s, a) s.setPosition(0) assert s.readAll() == "[1, 3, 5]"
-
proc `$$`[T](x: T): string
-
Returns a string representation of
x
(serialization, marshalling).Note: to serialize
x
to JSON use$(%x)
from thejson
module.Example:
Source Edittype Foo = object id: int bar: string let x = Foo(id: 1, bar: "baz") ## serialize: let y = $$x assert y == """{"id": 1, "bar": "baz"}"""
-
proc to[T](data: string): T
-
Reads data and transforms it to a type
T
(deserialization, unmarshalling).Example:
Source Edittype 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"
© 2006–2021 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/marshal.html