Rand Stats

JSON::Unmarshal

zef:raku-community-modules

Actions Status

NAME

JSON::Unmarshal

Make JSON from an Object (the opposite of JSON::Marshal)

SYNOPSIS

use JSON::Unmarshal;

class SomeClass {
    has Str $.string;
    has Int $.int;
}

my $json = '{ "string" : "string", "int" : 42 }';

my SomeClass $object = unmarshal($json, SomeClass);

say $object.string; # -> "string"
say $object.int;    # -> 42

DESCRIPTION

This provides a single exported subroutine to create an object from a JSON representation of an object.

It only initialises the "public" attributes (that is those with accessors created by declaring them with the '.' twigil. Attributes without acccessors are ignored.

unmarshal Routine

unmarshal has the following signatures:

The signatures with associative and positional JSON objects are to be used for pre-parsed JSON data obtained from a different source. For example, this may happen when a framework deserializes it for you.

The following named arguments are supported:

Manual Unmarshalling

It is also possible to use is unmarshalled-by trait to control how the value is unmarshalled:

use JSON::Unmarshal

class SomeClass {
    has Version $.version is unmarshalled-by(-> $v { Version.new($v) });
}

my $json = '{ "version" : "0.0.1" }';

my SomeClass $object = unmarshal($json, SomeClass);

say $object.version; # -> "v0.0.1"

The trait has two variants, one which takes a Routine as above, the other a Str representing the name of a method that will be called on the type object of the attribute type (such as "new",) both are expected to take the value from the JSON as a single argument.

INSTALLATION

Assuming you have a working Raku installation you should be able to install this with zef :

# From the source directory

zef install .

# Remote installation

zef install JSON::Unmarshal

SUPPORT

Suggestions/patches are welcomed via github at

https://github.com/raku-community-modules/JSON-Unmarshal

COPYRIGHT AND LICENSE

Copyright 2015-2017 Tadeusz Sośnierz Copyright 2022 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

Please see the LICENCE file in the distribution