NAME

JSON::String - Automatically change a JSON string when a data structure changes

SYNOPSIS

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"] }'

DESCRIPTION

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.

CONSTRUCTOR

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.

Methods

JSON::String->codec(); # returns a JSON instance
JSON::String->codec($obj);

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.

Mechanism

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.

Diagnostics

Error conditions are signalled with exceptions.

Error encoding data structure: %s

The codec's encode() method threw an exception when encoding the data structure.

Cannot handle %s reference

JSON::String->tie() was passed a string that did not decode to either a hashref or arrayref.

Expected plain string, but got reference

JSON::String->tie() was passed a reference to something instead of a string.

Expected string, but got <undef>

JSON::String->tie() was passed undef instead of a string.

Expected non-empty string

JSON::String->tie() was passed an empty string.

SEE ALSO

JSON::String::ARRAY, JSON::String::HASH, JSON

AUTHOR

Anthony Brummett <brummett@cpan.org>

COPYRIGHT

Copyright 2015, Anthony Brummett. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.