NAME
JSON::Simple - Perl extension for easily producing and parsing JSON.
SYNOPSIS
use JSON::Simple;
$json = to_json( $complex_data_structure ); # procudes JSON
$data = parse_json( $json ); # parses JSON
# -- OR: --
use JSON::Simple(':file'); # load only file-related
# subroutines.
json_to_file $filename, $data; # store it in a file
$data = json_from_file $filename; # read JSON from file
# -- OR: --
use JSON::Simple(':all'); # load all subroutines
DESCRIPTION
JSON (JavaScript Object Notation, http://www.json.org) is a simple to use format for data exchange, and actually a subset of JavaScript. JSON::Simple is a module that allows easy production of valid JSON from complex Perl data structures, and easy parsing of JSON into such data structures.
JSON::Simple is written out of personal discontent with the interfaces of existing JSON modules. JSON being a simple format, any modules dealing with it should be simple to use as well.
Exported subroutines
By default JSON::Simple exports two subroutines. to_json
, to_pretty_json
, and from_json
. Two more subroutines are available on request. They are json_to_file
and json_from_file
.
Two other subroutines aren't exported but they're accessable by their full names: JSON::Simple::true
and JSON::Simple::false
. They're discussed in-depth in "Boolean values".
Easy importing of subroutines can be done through:
# to_json and parse_json:
use JSON::Simple;
# json_to_file and json_from_file:
use JSON::Simple (':file')
# load all:
use JSON::Simple (':all')
to_json
my $json = to_json( $data );
Produces JSON from an arrayref or hashref.
Will croak when it runs into data that's not representable in JSON. This normally includes blessed references and things that are neither an arrayref, a hashref, a string, a number, or an instance of the the special JSON::Simple::Boolean class.
parse_json
my $data = parse_json( $json );
Given a string of valid JSON, parse_json converts that JSON into a native Perl data structure.
Will croak on invalid JSON.
json_to_file
json_to_file( $filepath, $data) or die "Couldn't dump: $!";
Produces JSON from an arrayref or hashref and stores it in the specified file.
Will croak when it runs into data that's not representable in JSON. This normally includes blessed references and things that are neither an arrayref, a hashref, a string, a number, or an instance of the the special JSON::Simple::Boolean class.
json_from_file
$data = json_fron_file( $filepath ) or die "Couldn't read: $!";
Loads a file into memory, tries to parse it as JSON, and builds a native Perl data structure out of it.
Will croak on invalid JSON.
JSON::Simple::true
Returns a JSON::Simple::Boolean object representing a boolean true
.
In-depth information can be found at "Boolean values".
JSON::Simple::false
Returns a JSON::Simple::Boolean object representing a boolean false
.
In-depth information can be found at "Boolean values".
CONFIGURATION
$JSON::Simple::indent
How many spaces to use for one level of indentation when pretty-formatting JSON. Defaults to 4.
$JSON::Simple::max_depth
Defines how deep JSON::Simple should go into a data structure. Since JSON doesn't really support structures with circular references, but Perl does, anything with a circular reference will make JSON::Simple go into an endless loop until your computer runs out of memory.
max_depth helps you prevent that, as JSON::Simple will croak when it is asked to go deeper into the structure than max_depth.
Defaults to 49, since I emperically discovered that Perl will begin to throw warnings at you about deep recursion if it's higher.
$JSON::Simple::pretty
If set to a true value, to_json() and json_to_file() will pretty-format the JSON they produce.
Defaults to 1.
$JSON::Simple::sortkeys
Like keys of hashes in Perl, names of name/value pairs in JSON objects aren't bound to come in any specific order. This variablke, however, tells JSON::Simple to make an attempt at somehow sorting the keys in the produces JSON anyway.
Set to a true value to enable, or to false to disable.
Defaults to 1. Even though the sorting gives a little overhead, output is so much more consistent if name/value pairs come in a predicable order that I think it's worth it.
MAPPING
From Perl to JSON
In Perl In JSON FORMAT
===================================================================
Array reference Array [ELEMENT, ...]
Hash reference Object {"NAME": VALUE, ...}
String String "VALUE"
Number Number e.g. 10, or 3.14, ...
JSON::Simple::Boolean
blessed reference Boolean true or false
Other reference (will throw a fatal error)
undef null null
From JSON to Perl
In JSON In Perl
===================================================================
Array Array reference
Object Hash reference
String String
Number Number
Boolean JSON::Simple::Boolean blessed reference
null undef
Boolean values
JSON, being a subset of JavaScript, supports native booleans. Perl doesn't, so JSON::Simple uses a workaround to represent booleans in Perl. JSON booleans become JSON::Simple::Boolean (JSB) objects. Each JSB object takes a value of either true or false. Through overloading, JSB knows to return a false value in boolean context and a string (either true or false) when it's interpolated in a string.
A cool side effect of the JSB design is that you're now effectively able to use these boolean values in your Perl data structure:
my $hotel_room = {
number => 414,
floor => 4,
available => JSON::Simple::false
};
# translates to JSON as {"number": 414, "floor": 4, "available": false}
if ( $hotel_room->{available} ) {
....
}
There are two ways to change the JSB object's value. Either you replace it with another JSB object:
$hotel_room->{available} = JSON::Simple::true;
# This is short-hand for:
$hotel_room->{available} = JSON::Simple::Boolean->true;
Or you just tell the JSB object which value you want it to assume:
$hotel_room->{available}->true;
Using JSB for a relatively simple thing as this sounds overcomplicated, but in fact it's not. Other designs were considered, but each of them has drawbacks that the JSB design overcomes.
- Use 1 and 0 for true and false
-
If the JSON parser finds a
true
, it could translate it to 1 and afalse
to 0. That would work, but if you then convert the data structure back to JSON again, JSON::Simple wouldn't know that these 1s and 0s were supposed to mean true and false. JSB removes the ambiguity. - Use \1 and \0 for true and false
-
Instead of using plain 1s and 0s for true and false, it would be possible to use references to 1 and 0 for boolean values.
Initially that was the design, but that would force you to write code like
if ( ${ $hotel_room-
{available} } )>. Having you dereference just because you want to check for trueness or falseness of a variable doesn't sound right, does it? - Use undef for false
-
No go. Perl's
undef
and JSON'snull
are so alike that undef can't mean anything else than null. That, or JSON::Simple wouldn't be so simple anymore.
BUGS AND CAVEATS
Unicode support is flawed.
Version 0.01 croaks (throws a fatal error) every time in runs into something it doesn't recognize. JSON::Simple will be more forgiving in a next version.
SEE ALSO
Introducing JSON: http://www.json.org/
RFC 4627: http://tools.ietf.org/html/rfc4627
CONTRIBUTERS
Author: P. Ramakers <pramakers@gmail.com> http://www.perlmonks.org/?node=muba
COPYRIGHT AND LICENSE
Copyright (C) 2011 by P. Ramakers
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.12.0 or, at your option, any later version of Perl 5 you may have available.