NAME

SYNOPSIS

DESCRIPTION

JSON::Tiny is a minimalistic standalone adaptation of Mojo::JSON, from the Mojolicious framework. It is a single-source-file module with under 300 lines of code and core-only dependencies.

Features include transparent Unicode support, speed, small memory footprint, and a minimal code base ideal for bundling or inlining. Along with Mojo:JSON, it is among the fastest pure-Perl implementations of RFC 7159.

JSON::Tiny supports normal Perl data types like scalar, array reference, hash reference, and will try to call the TO_JSON method on blessed references, or stringify them if it doesn't exist.

Differentiating between strings and numbers in Perl is hard; depending on how it has been used, a scalar can be both at the same time. The string value has a higher precedence unless both representations are equivalent.

[1, -2, 3] -> [1, -2, 3]
{"foo": "bar"} -> {foo => 'bar'}

Literal names will be translated to and from JSON::Tiny constants or a similar native Perl value.

true -> JSON::Tiny->true
false -> JSON::Tiny->false
null -> undef

Scalar references will be used to generate Booleans, based on if their values are true or false.

\1 => true
\0 => false

The two Unicode whitespace characters u2028 and u2029 will always be escaped to make JSONP easier, and the character / to prevent XSS attacks.

FUNCTIONS

JSON::Tiny implements the following functions, which can be imported individually.

decode_json

my $value = decode_json $bytes;

Decode JSON to Perl value and die if decoding fails.

encode_json

my $bytes = encode_json {foo => 'bar'};

Encode Perl value to JSON.

false

my $false = false;

False value, used because Perl has no equivalent.

from_json

my $value = from_json $chars;

Decode JSON text that is not UTF-8 encoded to Perl value and die if decoding fails.

j

Encode Perl data structure (which may only be an array reference or hash reference) or decode JSON. An undef return value indicates a bare null. Dies if decoding fails.

to_json

my $chars = to_json {i => '♥ Perl'};

Encode Perl value to JSON text without UTF-8 encoding it.

true

my $true = true;

True value, used because Perl has no native equivalent.

More on Booleans

A reference to a scalar (even if blessed) is encoded as a Boolean value unless it has a TO_JSON method.

my $json = $j->encode( { b => \1, a => \0 } ); # {"b":true,"a":false}

Boolean false and true values returned when JSON is decoded are JSON::Tiny::_Bool objects with overloaded stringification.

Advanced option: Users requiring a plain old literal 0 or 1, may set $JSON::Tiny::FALSE = 0; and $JSON::Tiny::TRUE = 1;. Any value, including blessed references will work. This must be set prior to calling a JSON decoding function. Use local to limit scope.

ACKNOWLEDGEMENTS

Mojolicious team for its lightweight JSON implementation. This module was adapted from Mojo::JSON because it is robust, minimal, and well tested. Mojo::JSON's tests were also adapted to a dependency-free design.