# marshal

Dark Mode

- Manual
- Standard library
- Index

Search:
Group by:

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

- streams module
- json module

# Imports

streams, typeinfo, json, intsets, tables, unicode

# Procs

    proc load[T](s: Stream; data: var T)

  Loads `data` from the stream `s`. Raises `IOError` in case of an error.

  Examples:

      import
        marshal, 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.

  Examples:

      import
        marshal, streams

      var s = newStringStream("")
      var a = [1, 3, 5]
      store(s, a)
      s.setPosition(0)
      assert s.readAll() == "[1, 3, 5]"

  Source Edit

    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.

  Examples:

      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

  Reads data and transforms it to a type `T` (deserialization, unmarshalling).

  Examples:

      type
        Foo = object
          id: int
          bar: string

      let y = """{"id": 1, "bar": "baz"}"""
      assert typeof(y) is string
      ## deserialize to type 'Foo':
      let z = to[Foo](y)
      assert typeof(z) is Foo
      assert z.id == 1
      assert z.bar == "baz"

  Source Edit