JSON::String - Automatically change a JSON string when a data structure changes
my $json_string = q({ a: 1, b: 2, c: [ 4, 5, 6 ] }); my $data = JSON::String->tie($json_string); @{$data->{c}} = qw(this data changed); # $json_string now contains '{ a: 1, b: 2, c: ["this", "data", "changed"] }'
This module constructs a data structure that, when changed, automatically changes the original string's contents to match the new data. Hashrefs and arrayrefs are supported, and their values can be scalars, hashrefs or arrayrefs.
The JSON format does not handle recursive data, and an exception will be thrown if the data structure is changed such that it has a loop.
my $data = JSON::String->tie($json_string);
Returns either a hashref or arrayref, depending on the input JSON string. The string passed in must by valid JSON encoding either an arrayref or hashref, otherwise it will throw an exception.
The returned data structure is tied to the string such that when the data changes, the JSON string stored in the variable will be changed to reflect the new data. If the string changes, the data structure will _not_ change.
Get or change the JSON codec object. The initial codec is created with JSON->new->canonical()
Any object can be used as the codec as long as it has encode() and decode() methods. A data structure's codec does not change after it is created. If the class's codec changes after creation, the data structure will continue to use whatever codec was active when it was created.
encode()
decode()
This module uses Perl's tie() mechanism to perform its magic. The hash- and arrayrefs that make up the returned data structure are references to tied hashes and arrays. When their data changes, the top-level data structure is re-encoded and stored back in the original variable.
tie()
Error conditions are signalled with exceptions.
The codec's encode() method threw an exception when encoding the data structure.
JSON::String->tie() was passed a string that did not decode to either a hashref or arrayref.
JSON::String->tie() was passed a reference to something instead of a string.
JSON::String->tie() was passed undef instead of a string.
JSON::String->tie() was passed an empty string.
JSON::String::ARRAY, JSON::String::HASH, JSON
Anthony Brummett <brummett@cpan.org>
Copyright 2015, Anthony Brummett. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
To install JSON::String, copy and paste the appropriate command in to your terminal.
cpanm
cpanm JSON::String
CPAN shell
perl -MCPAN -e shell install JSON::String
For more information on module installation, please visit the detailed CPAN module installation guide.