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
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!
See also
Procs
proc `$$`[T](x: 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 load[T](s: Stream; data: var T)
-
Loads data from the stream s. Raises IOError in case of an error.
Example:
import std/streams var s = newStringStream("[1, 3, 5]") var a: array[3, int] load(s, a) assert a == [1, 3, 5]
Source Edit proc store[T](s: Stream; data: T)
-
Stores data into the stream s. Raises IOError in case of an error.
Example:
import std/streams var s = newStringStream("") var a = [1, 3, 5] store(s, a) s.setPosition(0) assert s.readAll() == "[1, 3, 5]"
Source Edit proc to[T](data: string): T
-
Reads data and transforms it to a type 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