NAME

JSON::Tiny - Minimalistic JSON. No dependencies.

SYNOPSIS

# Encode and decode JSON
use JSON::Tiny;

my $json  = JSON::Tiny->new;
my $bytes = $json->encode({foo => [1, 2], bar => 'hello!', baz => \1});
my $hash  = $json->decode($bytes);

# Check for errors
my $json = JSON::Tiny->new;
if(defined(my $hash = $json->decode($bytes))) { say $hash->{message} }
else { say 'Error: ', $json->error }

# Use the alternative interface
use JSON::Tiny 'j';
my $bytes = j({foo => [1, 2], bar => 'hello!', baz => \1});
my $hash  = j($bytes);

DESCRIPTION

JSON::Tiny is a standalone adaptation of Mojo::JSON, from the Mojolicious framework. It has been adapted as a single-source-file module of under 350 lines of code and core-only dependencies.

Key features include relaxed JSON handling, transparent Unicode support, speed, small memory footprint, and a minimal code base ideal for bundling or inlining.

Mojo::JSON was chosen as a model because it is robust, minimal, and well tested. Mojo::JSON's tests were also adapted to a design free of non-core dependencies.

Much of this document is adapted directly from Mojo::JSON.

JSON::Tiny is a minimalistic and relaxed implementation of RFC 4627. While it is possibly the fastest pure-Perl JSON parser available, you should not use it for validation.

It 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.

[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. In addition Scalar references will be used to generate booleans, based on if their values are true or false.

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

Decoding UTF-16 (LE/BE) and UTF-32 (LE/BE) will be handled transparently, encoding will only generate UTF-8. The two Unicode whitespace characters u2028 and u2029 will always be escaped to make JSONP easier.

FUNCTIONS

JSON::Tiny implements the following functions.

j

my $bytes = j([1, 2, 3]);
my $bytes = j({foo => 'bar'});
my $array = j($bytes);
my $hash  = j($bytes);

Encode Perl data structure or decode JSON and return undef if decoding fails.

Dies with a JSON::Tiny::error message on decode failure.

ATTRIBUTES

JSON::Tiny implements the following attributes.

error

my $err = $json->error;
$json   = $json->error('Parser error');

Parser errors.

METHODS

JSON::Tiny implements the following methods.

new

my $json = JSON::Tiny->new;

Instantiate a JSON::Tiny object.

decode

my $array = $json->decode($bytes);
my $hash  = $json->decode($bytes);

Decode JSON to Perl data structure and return undef if decoding fails.

encode

my $bytes = $json->encode([1, 2, 3]);
my $bytes = $json->encode({foo => 'bar'});

Encode Perl data structure to JSON.

false

my $false = JSON::Tiny->false;
my $false = $json->false;

False value, used because Perl has no native equivalent.

true

my $true = JSON::Tiny->true;
my $true = $json->true;

True value, used because Perl has no native equivalent.

More on Booleans

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

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

The Boolean false and true values returned when JSON is decoded are JSON::Tiny::_Bool objects with stringification and numeric overloading. As an advanced option, if the user requires a plain old literal 0 or 1, setting $JSON::Tiny::FALSE = 0; and $JSON::Tiny::TRUE = 1;, or to some other value, including blessed references prior to calling the decode method will have the desired effect. Using local to prevent the change from causing errors at a distance is probably a very good idea.

It's Tiny

Comparing JSON::Tiny with JSON::PP from the JSON distribution:

  • JSON::PP is configurable, and comparatively complex. JSON::Tiny offers sane defaults, and nothing to configure.

  • Installation: cpanm JSON::PP vs cpanm JSON::Tiny: JSON::PP: 5.2 seconds. JSON::Tiny: 1.9 seconds (including download).

  • Minimal Dependencies: Both JSON::PP and JSON::Tiny only use core dependencies. JSON::Tiny requires Perl 5.8.4, while JSON::PP requires 5.6.

  • Simple Design: JSON has 2254 lines of code in six modules and five files, and a dist tarball of 84KB. JSON::Tiny has 350 lines of code; a single module in a single file. It can be easily embedded within existing code. The tarball is 18KB.

  • Simple Interface: JSON::PP has about 42 functions and methods. JSON::Tiny has seven.

  • Fast Performance (Benchmarks):

               Rate   JSON_PP JSON_Tiny
    JSON_PP   288/s        --      -62%
    JSON_Tiny 767/s      166%        --

    The benchmark script is included in this distribution's examples/ folder. JSON will automatically use JSON::XS if it's available. In that case, JSON::XS wins, but it's XS.

    Because JSON::Tiny doesn't pull in as many external modules, and splits the POD into a separate file to minimize the source-code file size, startup time for JSON::Tiny is slightly faster than for the JSON module. But, the startup time in either case should only be a factor in applications such as CGI, where processes may be started many times per second.

  • Light Memory Needs: From the distribution's examples/ folder, json_pp_alone.pl and json_tiny_alone.pl were tested, first with Devel::MemoryTrace::Light, and then with http://valgrind.org/valgrind. The results were as follows:

    • JSON (JSON::PP): Devel::MemoryTrace::Lite: About 1.7MB. valgrind: about 6.1MB.

    • JSON::Tiny: Devel::MemoryTrace::Lite: About 1.1MB. valgrind: about 5.4MB.

    These utilities have different methods of measuring memory use, but both show JSON::Tiny is 600-700KB lighter than JSON::PP.

CONFIGURATION AND ENVIRONMENT

Zero configuration.

DEPENDENCIES

Perl 5.8.4 or newer.

INCOMPATIBILITIES

Incompatible with Exporter versions that predate Perl 5.8.4. Perl 5.8.4 shipped with Exporter v5.58. Exporter became dual-life as of v5.59, so upgrading Exporter to v5.59 or newer should allow JSON::Tiny to run on Perl versions older than 5.8.4.

AUTHOR

David Oswald, <davido at cpan.org>

The code and tests were adapted with minimal changes from Mojo::JSON.

SUPPORT

Support requests should be directed to the author. Direct bug reports to CPAN's Request Tracker (RT).

You can find documentation for this module with the perldoc command.

perldoc JSON::Tiny

You may look for additional information at:

ACKNOWLEDGEMENTS

Thank-you to the Mojolicious team for producing an excellent product that offers light-weight implementations of many useful tools. This module wouldn't exist or be as well designed and tested if it weren't for Mojolicious.

Also to Randal Schwartz for showing the Los Angeles Perl Mongers (Sept 2012) his embeddable pure-regexp JSON parser, and explaining it on PerlMonks (http://www.perlmonks.org/?node_id=995856). He wasn't involved in JSON::Tiny, but it was the exploration of alternatives to his solution that led to this fork of Mojolicious's JSON parser.

LICENSE AND COPYRIGHT

Copyright 2012 David Oswald.

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.

See http://www.perlfoundation.org/artistic_license_2_0 for more information.

SEE ALSO

JSON, JSON::PP, JSON::XS, Mojo::JSON, Mojolicious.