pax_global_header00006660000000000000000000000064144615451710014522gustar00rootroot0000000000000052 comment=246f7a3591f24fbdcd4de25583a5b26b3d3b7a12 raku-json-unmarshal-0.15/000077500000000000000000000000001446154517100153505ustar00rootroot00000000000000raku-json-unmarshal-0.15/.github/000077500000000000000000000000001446154517100167105ustar00rootroot00000000000000raku-json-unmarshal-0.15/.github/workflows/000077500000000000000000000000001446154517100207455ustar00rootroot00000000000000raku-json-unmarshal-0.15/.github/workflows/test.yml000066400000000000000000000012361446154517100224510ustar00rootroot00000000000000name: test on: push: branches: - '*' tags-ignore: - '*' pull_request: jobs: raku: strategy: matrix: os: - ubuntu-latest - macos-latest - windows-latest raku-version: - 'latest' runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: Raku/setup-raku@v1 with: raku-version: ${{ matrix.raku-version }} - name: Install Dependencies run: zef install --/test --test-depends --deps-only . - name: Install App::Prove6 run: zef install --/test App::Prove6 - name: Run Tests run: prove6 -I. t raku-json-unmarshal-0.15/.gitignore000066400000000000000000000003261446154517100173410ustar00rootroot00000000000000/blib/ /.build/ _build/ cover_db/ inc/ Build !Build/ Build.bat .last_cover_stats /Makefile /Makefile.old /MANIFEST.bak /META.yml /META.json /MYMETA.* nytprof.out /pm_to_blib *.o *.bs /_eumm/ .precomp *.iml .idea/* raku-json-unmarshal-0.15/Changes000066400000000000000000000026671446154517100166560ustar00rootroot00000000000000Revision history for JSON-Unmarshal {{$NEXT}} 0.15 2023-07-30T16:39:11-04:00 - Nominalize type objects first if they're nominalizable - Clarify the rule defining deserializable type objects: a nominal with at least one public attribute - Consider `is build`-marked attributes as public 0.14 2023-07-25T18:54:32+02:00 - Tighten up the _unmarshal(%, Mu) candidate to not match Positional|Associative target - Panic on Associate data for Positional target - Add test of META6 in GH action as a canary 0.13 2023-07-20T22:09:02-04:00 - When reporting unsued JSON keys report the target type too - Fix a bug with incorrect setting of warn/throw mode 0.12 2023-07-19T17:26:55-04:00 - Extend safety measure by introducing `:warn` and `:die`/`:throw` named arguments - Allow non-`Any` classes to be deserialized - Added some missing pieces to the documentation 0.11 2022-07-25T10:26:41+02:00 - Fix trait issue, Siavash++ - Add some tags 0.10 2022-07-10T20:49:14-04:00 - Fix a problem with nominalizables when their nominal is a non-default class 0.09 2022-07-10T19:17:33-04:00 - Support for nominalizable types like definites (smiley types) and coercions - Support for input from pre-desrialized data like hashes or arrays obtained from an earlier from-json call - Throw specialized `JSON::Unmarshal::X::CannotUnmarshall` exception on errors with more detailed information about the error raku-json-unmarshal-0.15/LICENSE000066400000000000000000000213061446154517100163570ustar00rootroot00000000000000 The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. raku-json-unmarshal-0.15/META6.json000066400000000000000000000011571446154517100170630ustar00rootroot00000000000000{ "auth": "zef:raku-community-modules", "authors": [ "Tadeusz Sośnierz", "Raku Community" ], "build-depends": [ ], "depends": [ "JSON::Fast", "JSON::Name:ver<0.0.6+>", "JSON::OptIn" ], "description": "Turn JSON into objects", "license": "Artistic-2.0", "name": "JSON::Unmarshal", "perl": "6.c", "provides": { "JSON::Unmarshal": "lib/JSON/Unmarshal.rakumod" }, "raku": "6.c", "resources": [ ], "source-url": "https://github.com/raku-community-modules/JSON-Unmarshal.git", "tags": [ "JSON", "UNMARSHALL" ], "test-depends": [ ], "version": "0.15" } raku-json-unmarshal-0.15/README.md000066400000000000000000000065201446154517100166320ustar00rootroot00000000000000[![Actions Status](https://github.com/raku-community-modules/JSON-Unmarshal/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/JSON-Unmarshal/actions) 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: * `unmarshal(Str:D $json, Positional $obj, *%)` * `unmarshal(Str:D $json, Associative $obj, *%)` * `unmarshal(Str:D $json, Mu $obj, *%)` * `unmarshal(%json, $obj, *%)` * `unmarshal(@json, $obj, *%)` 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: * **`Bool :$opt-in`** When falsy then all attributes of a class are deserialized. When *True* then only those marked with `is json` trait provided by `JSON::OptIn` module are taken into account. * **`Bool :$warn`** If set to *True* then the module will warn about some non-critical problems like unsupported named arguments or keys in JSON structure for which there no match attributes were found. * **`Bool :$die`** or **`Bool :$throw`** This is two aliases of the same attribute with meaning, similar to `:warn`, but where otherwise a waning would be issued the module will throw an exception. 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](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 raku-json-unmarshal-0.15/dist.ini000066400000000000000000000002731446154517100170160ustar00rootroot00000000000000name = JSON-Unmarshal [ReadmeFromPod] ; enabled = false filename = lib/JSON/Unmarshal.rakumod [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/test.yml raku-json-unmarshal-0.15/lib/000077500000000000000000000000001446154517100161165ustar00rootroot00000000000000raku-json-unmarshal-0.15/lib/JSON/000077500000000000000000000000001446154517100166675ustar00rootroot00000000000000raku-json-unmarshal-0.15/lib/JSON/Unmarshal.rakumod000066400000000000000000000253241446154517100222130ustar00rootroot00000000000000use v6; use JSON::Name:ver<0.0.6+>; use JSON::OptIn; use JSON::Fast; unit module JSON::Unmarshal; =begin pod =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. =head2 C Routine C has the following signatures: =item C =item C =item C =item C =item C 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: =begin item B> When falsy then all attributes of a class are deserialized. When I then only those marked with C trait provided by C module are taken into account. =end item =begin item B> If set to I then the module will warn about some non-critical problems like unsupported named arguments or keys in JSON structure for which there no match attributes were found. =end item =begin item B> or B> This is two aliases of the same attribute with meaning, similar to C<:warn>, but where otherwise a waning would be issued the module will throw an exception. =end item =head2 Manual Unmarshalling It is also possible to use C 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* : =begin code # From the source directory zef install . # Remote installation zef install JSON::Unmarshal =end code =SUPPORT Suggestions/patches are welcomed via github at L =head1 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 =end pod our class X::CannotUnmarshal is Exception { has Attribute:D $.attribute is required; has Any:D $.json is required; has Mu:U $.type is required; has Mu:U $.target is required; has Str $.why; method message { "Cannot unmarshal {$.json.raku} into type '{$.type.^name}' for attribute {$.attribute.name} of '{$.target.^name}'" ~ ($.why andthen ": $_" orelse "") } } our class X::UnusedKeys is Exception { has Set:D $.unused-keys is required; has Mu:U $.type is required; method message { my $sfx = $!unused-keys.elems > 1 ?? "s" !! ""; "No attribute$sfx found in '" ~ $!type.^name ~ "' for JSON key$sfx " ~ $!unused-keys.keys.sort.map("'" ~ * ~ "'").join(", ") } } enum ErrorMode ; my class UnmarshallParams { has Bool $.opt-in; has ErrorMode $.error-mode; } role CustomUnmarshaller does JSON::OptIn::OptedInAttribute { method unmarshal($value, Mu:U $type) { ... } } role CustomUnmarshallerCode does CustomUnmarshaller { has &.unmarshaller is rw; method unmarshal($value, Mu:U $) { # the dot below is important otherwise it refers # to the accessor method self.unmarshaller.($value); } } role CustomUnmarshallerMethod does CustomUnmarshaller { has Str $.unmarshaller is rw; method unmarshal($value, Mu:U $type) { my $meth = self.unmarshaller; $type."$meth"($value); } } multi sub trait_mod: (Attribute $attr, :&unmarshalled-by!) is export { $attr does CustomUnmarshallerCode; $attr.unmarshaller = &unmarshalled-by; } multi sub trait_mod: (Attribute $attr, Str:D :$unmarshalled-by!) is export { $attr does CustomUnmarshallerMethod; $attr.unmarshaller = $unmarshalled-by; } proto sub panic(Any, Mu, |) {*} multi sub panic($json, Mu \type, X::CannotUnmarshal:D $ex) { $ex.rethrow } multi sub panic($json, Mu \type, Exception:D $ex) { samewith($json, type, $ex.message) } multi sub panic($json, Mu \type, Str $why?) { X::CannotUnmarshal.new( :$json, :type(type.WHAT), :attribute($*JSON-UNMARSHAL-ATTR), :$why, :target($*JSON-UNMARSHAL-TYPE) ).throw } my sub maybe-nominalize(Mu \obj) is pure is raw { obj.HOW.archetypes.nominalizable ?? obj.^nominalize !! obj } multi _unmarshal(Any:U, Mu $type) { $type; } multi _unmarshal(Any:D $json, Int) { if $json ~~ Int { return Int($json) } panic($json, Int) } multi _unmarshal(Any:D $json, Rat) { CATCH { default { panic($json, Rat, $_); } } return Rat($json); } multi _unmarshal(Any:D $json, Numeric) { if $json ~~ Numeric { return Num($json) } panic($json, Numeric) } multi _unmarshal($json, Str) { if $json ~~ Stringy { return Str($json) } else { Str; } } multi _unmarshal(Any:D $json, Bool) { CATCH { default { panic($json, Bool, $_); } } return Bool($json); } subset PosNoAccessor of Positional where { ! maybe-nominalize($_).^attributes.first({ .has_accessor || .is_built }) }; multi _unmarshal(%json, PosNoAccessor $obj ) { panic(%json, Positional, "type mismatch"); } # A class-like type is the one we can instantiate and it has at least one public or `is build`-marked attribute. subset ClassLike of Mu where -> Mu \type { .HOW.archetypes.nominal && .HOW.^can('attributes') && .^attributes.first({ $_ ~~ Attribute && (.has_accessor || .is_built) }) given maybe-nominalize(type) }; multi _unmarshal(%json, ClassLike $obj is raw) { my %args; my $params = $*JSON-UNMARSHALL-PARAMS; my SetHash $used-json-keys .= new; my \type = $obj.HOW.archetypes.nominalizable ?? $obj.^nominalize !! $obj.WHAT; my %local-attrs = type.^attributes(:local).map({ $_.name => $_.package }); for type.^attributes -> $attr { my $*JSON-UNMARSHAL-ATTR = $attr; if %local-attrs{$attr.name}:exists && !(%local-attrs{$attr.name} === $attr.package ) { next; } if $params.opt-in && $attr !~~ JSON::OptIn::OptedInAttribute { next; } my $attr-name = $attr.name.substr(2); my $json-name = do if $attr ~~ JSON::Name::NamedAttribute { $attr.json-name; } else { $attr-name; } if %json{$json-name}:exists { my Mu $attr-type := $attr.type; my $is-nominalizable = $attr-type.HOW.archetypes.nominalizable; $used-json-keys.set($json-name); %args{$attr-name} := do if $attr ~~ CustomUnmarshaller { $attr.unmarshal(%json{$json-name}, $attr-type) } elsif $is-nominalizable && $attr-type.HOW.archetypes.coercive && %json{$json-name} ~~ $attr-type { # No need to unmarshal, coercion will take care of it %json{$json-name} } else { _unmarshal(%json{$json-name}, $is-nominalizable ?? $attr-type.^nominalize !! $attr-type) } } } if ((my $err-mode = $params.error-mode) != EM_IGNORE) && (my $unused-keys = (%json.keys.Set (-) $used-json-keys)) { my $ex = X::UnusedKeys.new: :$unused-keys, :type(type); if $err-mode == EM_WARN { warn($ex.message) } else { $ex.throw } } type.new(|%args) } multi _unmarshal($json, @x) { my @ret := Array[@x.of].new; for $json.list -> $value { my $type = @x.of =:= Any ?? $value.WHAT !! @x.of; @ret.append(_unmarshal($value, $type)); } return @ret; } multi _unmarshal(%json, %x) { my %ret := Hash[%x.of].new; for %json.kv -> $key, $value { my $type = %x.of =:= Any ?? $value.WHAT !! %x.of; %ret{$key} = _unmarshal($value, $type); } return %ret; } multi _unmarshal(Any:D $json, Mu) { return $json } my sub _unmarshall-context(\obj, % (Bool :$opt-in, Bool :$warn, Bool :die(:$throw), *%extra), &code) is raw { if %extra { with "Unsupported arguments: " ~ %extra.keys.sort.map("'" ~ * ~ "'").join(", ") { $throw ?? die $_ !! warn $_ } } my $*JSON-UNMARSHAL-TYPE := obj.WHAT; my $*JSON-UNMARSHALL-PARAMS := UnmarshallParams.new: :$opt-in, error-mode => ($throw ?? EM_THROW !! ($warn ?? EM_WARN !! EM_IGNORE)); code() } proto unmarshal(Any:D, |) is export {*} multi unmarshal(Str:D $json, PosNoAccessor $obj, *%c) { _unmarshall-context $obj, %c, { my Any \data = from-json($json); if data ~~ Positional { return @(_unmarshal($_, $obj.of) for @(data)); } else { fail "Unmarshaling to type $obj.^name() requires the json data to be a list of objects."; } } } multi unmarshal(Str:D $json, Associative $obj, *%c) { _unmarshall-context $obj, %c, { my \data = from-json($json); if data ~~ Associative { return %(for data.kv -> $key, $value { $key => _unmarshal($value, $obj.of) }) } else { fail "Unmarshaling to type $obj.^name() requires the json data to be an object."; }; } } multi unmarshal(Str:D $json, Mu $obj, *%c) { _unmarshall-context $obj, %c, { _unmarshal(from-json($json), $obj.WHAT) } } multi unmarshal(%json, $obj, *%c) { _unmarshall-context $obj, %c, { _unmarshal(%json, $obj.WHAT) } } multi unmarshal(@json, $obj, *%c) { _unmarshall-context $obj, %c, { _unmarshal(@json, $obj.WHAT) } } # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/000077500000000000000000000000001446154517100156135ustar00rootroot00000000000000raku-json-unmarshal-0.15/t/010-basic.rakutest000066400000000000000000000042601446154517100207600ustar00rootroot00000000000000use Test; use JSON::Unmarshal; plan 25; class Dog { has Str $.name; has Str $.race; has Int $.age; } class Person { has Str $.name; has Int $.age; has Dog @.dogs; has Str %.contact; } my $json = q/ { "name" : "John Brown", "age" : 17, "contact" : { "email" : "jb@example.com", "phone" : "12345678" }, "dogs" : [{ "name" : "Roger", "race" : "corgi", "age" : 4 }, { "name" : "Panda", "race" : "wolfish", "age" : 13 }] } /; my $p = unmarshal($json, Person); isa-ok $p, Person; is $p.name, "John Brown"; is $p.age, 17; is $p.contact, 'jb@example.com'; is $p.contact, "12345678"; is $p.dogs.elems, 2; is $p.dogs[0].name, 'Roger'; is $p.dogs[0].race, 'corgi'; is $p.dogs[0].age, 4; is $p.dogs[1].name, 'Panda'; is $p.dogs[1].race, 'wolfish'; is $p.dogs[1].age, 13; # Tests for the un-typed cases class ArrayTest { has @.array; } $json = q/ { "array" : [ "one", 1, true, 42.3 ] } /; lives-ok { $p = unmarshal($json, ArrayTest) }, "unmarshal object with un-shaped array attribute"; is $p.array.elems, 4; is $p.array[0], "one"; is $p.array[1], 1; is $p.array[2], True; is $p.array[3], 42.3; class HashTest { has %.hash; } $json = q/ { "hash" : { "string" : "one", "int" : 1, "bool" : true, "rat" : 42.3 } } /; lives-ok { $p = unmarshal($json, HashTest) }, "unmarshal object with un-shaped hash attribute"; is $p.hash.keys.elems, 4; is $p.hash, "one"; is $p.hash, 1; is $p.hash, True; is $p.hash, 42.3; subtest "unmarshall named arguments", { plan 2; { my $warn-msg = ""; CONTROL { when CX::Warn { $warn-msg = .message; .resume } } unmarshal '{}', HashTest, :warn, :foo, :bar; like $warn-msg, /"Unsupported arguments: 'bar', 'foo'"/, "unsupported named arguments result in a warning with :warn"; } dies-ok { unmarshal '{}', HashTest, :die, :foo, :bar }, "it dies with unsupported named arguments and :die (or :throw)"; } done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/020-any.rakutest000066400000000000000000000014101446154517100204610ustar00rootroot00000000000000#!raku use v6; use Test; use JSON::Unmarshal; plan 16; class AnyAttributeClass { has $.any-attr; } my @tests = ( { json => '{ "any-attr" : 42 }', value => 42, type => Int }, { json => '{ "any-attr" : 4.2 }', value => 4.2, type => Rat }, { json => '{ "any-attr" : "42" }', value => '42', type => Str }, { json => '{ "any-attr" : true }', value => True, type => Bool }, ); for @tests -> $test { my $ret; lives-ok { $ret = unmarshal($test, AnyAttributeClass) }, "unmarshal { $test.^name }"; isa-ok $ret, AnyAttributeClass, "returns the right object"; is $ret.any-attr, $test, "attribute has the correct value"; isa-ok $ret.any-attr, $test, "and it is the right type"; } done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/030-null.rakutest000066400000000000000000000011671446154517100206560ustar00rootroot00000000000000#!/usr/bin/env raku use v6.*; use Test; use JSON::Unmarshal; plan 4; my Str $json = '{ "attr" : null }'; my @tests = %( "class" => class { has Int $.attr; }, description => "Int attribute" ), %( "class" => class { has Num $.attr; }, description => "Num attribute" ), %( "class" => class { has Rat $.attr; }, description => "Rat attribute" ), %( "class" => class { has Str $.attr; }, description => "Str attribute" ),; for @tests -> $test { my $obj; lives-ok { $obj = unmarshal($json, $test ) }, $test; } done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/040-types.rakutest000066400000000000000000000076641446154517100210610ustar00rootroot00000000000000#!raku use v6; use Test; use JSON::Unmarshal; sub test-typed($json, Mu \obj-class, Mu $expected, Str :$message is copy, Bool :$is-null) { my $type-name = $expected.^name; my $ret; $message //= "$type-name attribute from " ~ ($json ~~ Str ?? "JSON string" !! "a " ~ $json.^name); subtest $message => { plan 4; $ret = unmarshal($json, obj-class); lives-ok { $ret = unmarshal($json, obj-class) }, "unmarshal with $type-name typed attribute"; isa-ok $ret, obj-class.WHAT, "it's the right object type"; if $is-null { nok $ret.attr.defined, "and unefined"; isa-ok $ret.attr, $expected.WHAT, "and the correct type"; } else { ok $ret.attr.defined, "and defined"; is $ret.attr, $expected, "and the correct value"; } done-testing; } } class RatClass { has $.attr; } class NumClass { has Num $.attr; } class IntClass { has Int $.attr; } class BoolClass { has Bool $.attr; } class StrClass { has Str $.attr; } class IntDClass { has Int:D $.attr is required; } class IntCoerced { has Int() $.attr; } class IntDCoerced { has Int:D() $.attr is required; } class VersionDCoerced { has Version:D() $.attr is required; } class DateTimeDClass { has DateTime:D $.attr is required; } my @tests = [ '{ "attr" : 4.2 }', RatClass, 4.2, ], [ '{ "attr" : 4.2 }', NumClass, 4.2, ], [ '{ "attr" : 42 }', IntClass, 42, ], [ '{ "attr" : 42 }', IntDClass, 42, :message("Int:D attribute"), ], [ '{ "attr" : 42 }', IntCoerced, 42, :message("Int() attribute"), ], [ '{ "attr" : 42 }', IntDCoerced, 42, :message("Int:D() attribute"), ], [ '{ "attr" : "0.12.42" }', VersionDCoerced, v0.12.42, :message("Version:D() attribute") ], [ '{ "attr" : true }', BoolClass, True, ], [ '{ "attr" : false }', BoolClass, False, :message("Bool attribute with False") ], [ '{ "attr" : "foo" }', StrClass, "foo", ], [ '{ "attr" : null }', StrClass, Str, message => "Str attribute with 'null' in JSON", :is-null, ], [ '{ "attr": { "daycount": 59770, "month": 7, "timezone": -14400, "formatter": null, "hour": 20, "minute": 32, "year": 2022, "day": 10, "second": 12.345e0 } }', DateTimeDClass, DateTime.new(2022,7,10,20,32,12.345e0,:timezone(-14400)), :message("DateTime as a definite"), ], [ { attr => 4.2 }, RatClass, 4.2, ], [ { attr => 4.2 }, NumClass, 4.2, ], [ { attr => 42 }, IntClass, 42, ], [ { attr => True }, BoolClass, True, ], [ { attr => False }, BoolClass, False, :message("Bool attribute with False in JSON hash") ], [ { attr => "foo" }, StrClass, "foo", ], [ { attr => Nil }, StrClass, Str, message => "Str attribute with Nil in JSON hash", :is-null, ], ; plan 2+@tests; for @tests -> @test { my @pos = @test.grep( * !~~ Pair ); my %named = |@test.grep( * ~~ Pair ); test-typed |@pos, |%named; } throws-like { unmarshal('{"attr": null}', IntDClass ) }, X::TypeCheck::Assignment, "null into a definite dies"; class NastyCoercive { has Int(Rat) $.attr; } throws-like { unmarshal('{"attr": "13"}', NastyCoercive) }, X::CannotUnmarshal, :message(q«Cannot unmarshal "13" into type 'Int' for attribute $!attr of 'NastyCoercive'»), "unmarshalling into a wrong type throws"; done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/050-json-name.rakutest000066400000000000000000000007301446154517100215700ustar00rootroot00000000000000#!raku use v6; use lib 'lib'; use Test; use JSON::Unmarshal; use JSON::Name; plan 2; class TestClass { has $.nice-name is rw is json-name('666.evil.name'); } my $json = '{ "666.evil.name" : "some value we want" }'; my $obj; lives-ok { $obj = unmarshal($json, TestClass) }, "Unmarshal object with a json-name attribute"; is $obj.nice-name,"some value we want", "and we got the key back with the json name"; done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/060-lists_hashes.rakutest000066400000000000000000000022541446154517100223760ustar00rootroot00000000000000use Test; use JSON::Unmarshal; plan 18; class Dog { has Str $.name; has Str $.race; has Int $.age; } my $json = q/ [ { "name": "Roger", "race": "corgi", "age": 4 }, { "name": "Panda", "race": "wolfish", "age": 13 } ] /; my @dogs = unmarshal($json, Array[Dog]); ok @dogs ~~ Positional; isa-ok @dogs[0], Dog; is @dogs[0].name, "Roger"; is @dogs[0].race, "corgi"; is @dogs[0].age, 4; isa-ok @dogs[1], Dog; is @dogs[1].name, "Panda"; is @dogs[1].race, "wolfish"; is @dogs[1].age, 13; my $json-two = q/ { "good dog": { "name": "Roger", "race": "corgi", "age": 4 }, "also a good dog": { "name": "Panda", "race": "wolfish", "age": 13 } } /; my %dogs = unmarshal($json-two, Hash[Dog]); ok %dogs ~~ Associative; isa-ok %dogs{'good dog'}, Dog; is %dogs{'good dog'}.name, "Roger"; is %dogs{'good dog'}.race, "corgi"; is %dogs{'good dog'}.age, 4; isa-ok %dogs{'also a good dog'}, Dog; is %dogs{'also a good dog'}.name, "Panda"; is %dogs{'also a good dog'}.race, "wolfish"; is %dogs{'also a good dog'}.age, 13; raku-json-unmarshal-0.15/t/070-parameterised.rakutest000066400000000000000000000005771446154517100225410ustar00rootroot00000000000000#!raku use Test; use JSON::Unmarshal; plan 2; class C { has Str %.bla{subset :: of Str where any("ble", "blob")} }; my $res; lives-ok { $res = unmarshal( 「{"bla": {"ble": "bli"}}」, C); }, "unmarshal class with hash with subset constrained values"; is $res.bla , 'bli', "and the result is what is expected"; done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/080-trait.rakutest000066400000000000000000000050211446154517100210250ustar00rootroot00000000000000#!raku use v6; use Test; use JSON::Unmarshal; subtest { class VersionClassCode { has Version $.version is unmarshalled-by(-> $v { Version.new($v) }); } my $json = '{ "version" : "0.0.1" }'; my VersionClassCode $obj; lives-ok { $obj = unmarshal($json, VersionClassCode) }, "unmarshall with attrbute strait (code)"; isa-ok $obj.version, Version, "the attribute is the right kind of thing"; ok $obj.version.defined, "and it's defined"; is $obj.version, Version.new("0.0.1"), "and has the right value"; }, "unmarshalled-by trait with Code"; subtest { class VersionClassMethod { has Version $.version is unmarshalled-by('new'); } my $json = '{ "version" : "0.0.1" }'; my VersionClassMethod $obj; lives-ok { $obj = unmarshal($json, VersionClassMethod) }, "unmarshall with attrbute trait (method name)"; isa-ok $obj.version, Version, "the attribute is the right kind of thing"; ok $obj.version.defined, "and it's defined"; is $obj.version, Version.new("0.0.1"), "and has the right value"; }, "unmarshalled-by trait with Method name"; subtest { class Inner { has Str $.name is required; } class OuterClass { has Inner $.inner; } class OuterSubClass is OuterClass { has Inner $.inner is unmarshalled-by(-> $name { Inner.new(:$name) }); } my $json = '{ "inner" : "name" }'; my OuterSubClass $obj; lives-ok { $obj = unmarshal($json, OuterSubClass) }, "unmarshall with attrbute trait on sub-class"; isa-ok $obj.inner, Inner, "the attribute is the right kind of thing"; ok $obj.inner.defined, "and it's defined"; is $obj.inner.name, "name", "and has the right value"; }, "unmarshalled-by trait with inheritance"; subtest { class CustomArrayAttribute { class Inner { has Str $.name is required; } sub unmarshall-inners (@inners) { @inners.map(-> $name { Inner.new(:$name) }) } has Inner @.inners is unmarshalled-by(&unmarshall-inners); } my $json = '{ "inners" : [ "one", "two", "three" ] }'; my $obj; lives-ok { $obj = unmarshal $json, CustomArrayAttribute; }, "unmarshal with custom marshaller on positional attribute"; ok all($obj.inners) ~~ CustomArrayAttribute::Inner, "and all the objects in the array are correct"; is-deeply $obj.inners.map( *.name), , "and they have their names set correctly"; }, "unmarshalled-by on a positional attribute"; done-testing; # vim: expandtab shiftwidth=4 ft=raku raku-json-unmarshal-0.15/t/090-unused-keys.t000066400000000000000000000014141446154517100205620ustar00rootroot00000000000000use Test; use JSON::Unmarshal; plan 2; class Foo { has Int $.count; has Bool $.check; } my $json = '{"count": 42, "check": true, "description": "about something", "name": "fubar" }'; { my $warn-msg; CONTROL { when CX::Warn { $warn-msg = .message; .resume } } my Foo $foo = unmarshal $json, Foo, :warn; my $msg = "a warning produced for unsued JSON keys with :warn"; with $warn-msg { like $_, /"No attributes found " .* "'description', 'name'"/, $msg; } else { flunk $msg; } } throws-like { my Foo $foo = unmarshal $json, Foo, :throw; }, X::UnusedKeys, :unused-keys(.Set), "an exception is thrown for unsued JSON keys with :throw (or :die)"; raku-json-unmarshal-0.15/t/100-issue-7.rakutest000066400000000000000000000033661446154517100212010ustar00rootroot00000000000000use Test; use JSON::Unmarshal; plan 4; subtest { my class TestClass { has $.attribute where Positional|Associative; } my $obj; my $with-object-attr = '{ "attribute": { "foo" : "bar" } }'; lives-ok { $obj = unmarshal($with-object-attr, TestClass) }, "with object attribute"; is-deeply $obj.attribute, { foo => 'bar' }, "attribute got set correctly"; my $with-list-attr = '{ "attribute": [ "foo", "bar" ] }'; lives-ok { $obj = unmarshal($with-list-attr, TestClass) }, "with list attribute"; is-deeply $obj.attribute, [ "foo", "bar" ], "attribute got set correctly"; }, 'where subset with Junction type'; subtest { my class TestClass { has Str @.attribute; } my $with-object-attr = '{ "attribute": { "foo" : "bar" } }'; throws-like { unmarshal($with-object-attr, TestClass) }, X::CannotUnmarshal, "object passed for positional attribute"; }, 'positional vs associative mismatch'; subtest { my class TestClass does Positional { has Str $.string; } my $string-attribute = '{ "string" : "test value" }'; my $obj; lives-ok { $obj = unmarshal($string-attribute, TestClass) }, "unmarshal"; is $obj.string, 'test value', "got the attribute back"; }, 'class that does positional with pairwise constructor at top level'; subtest { my class TestClassPos does Positional { has Str $.string; } my class TestClass { has TestClassPos $.pos; } my $string-attribute = '{"pos" : { "string" : "test value" }}'; my $obj; lives-ok { $obj = unmarshal($string-attribute, TestClass) }, "unmarshal"; is $obj.pos.string, 'test value', "got the attribute back"; }, 'class that does positional with pairwise constructor as attribute'; raku-json-unmarshal-0.15/t/opt-in.t000066400000000000000000000010441446154517100172050ustar00rootroot00000000000000#!/usr/bin/env raku use Test; use JSON::Unmarshal; use JSON::OptIn; use JSON::Name; plan 3; class OptInClass { has Str $.not_opted_in = "original"; has Str $.opted_in is json; } my $json = '{ "not_opted_in" : "not original", "opted_in" : "something" }'; my $obj; lives-ok { $obj = unmarshal($json, OptInClass, :opt-in) }, 'unmarshal with opt-in'; is $obj.not_opted_in, 'original', "attribute not marked explicitly not populated from JSON"; is $obj.opted_in, 'something', "attribute marked is set"; done-testing; # vim: ft=raku