ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/XS.pm
(Generate patch)

Comparing JSON-XS/XS.pm (file contents):
Revision 1.139 by root, Thu May 23 09:31:32 2013 UTC vs.
Revision 1.144 by root, Mon Oct 28 23:19:54 2013 UTC

83this module usually compares favourably in terms of speed, too. 83this module usually compares favourably in terms of speed, too.
84 84
85=item * simple to use 85=item * simple to use
86 86
87This module has both a simple functional interface as well as an object 87This module has both a simple functional interface as well as an object
88oriented interface interface. 88oriented interface.
89 89
90=item * reasonably versatile output formats 90=item * reasonably versatile output formats
91 91
92You can choose between the most compact guaranteed-single-line format 92You can choose between the most compact guaranteed-single-line format
93possible (nice for simple line-based protocols), a pure-ASCII format 93possible (nice for simple line-based protocols), a pure-ASCII format
104use common::sense; 104use common::sense;
105 105
106our $VERSION = 2.34; 106our $VERSION = 2.34;
107our @ISA = qw(Exporter); 107our @ISA = qw(Exporter);
108 108
109our @EXPORT = qw(encode_json decode_json to_json from_json); 109our @EXPORT = qw(encode_json decode_json);
110
111sub to_json($) {
112 require Carp;
113 Carp::croak ("JSON::XS::to_json has been renamed to encode_json, either downgrade to pre-2.0 versions of JSON::XS or rename the call");
114}
115
116sub from_json($) {
117 require Carp;
118 Carp::croak ("JSON::XS::from_json has been renamed to decode_json, either downgrade to pre-2.0 versions of JSON::XS or rename the call");
119}
120 110
121use Exporter; 111use Exporter;
122use XSLoader; 112use XSLoader;
113
114use Types::Serialiser ();
123 115
124=head1 FUNCTIONAL INTERFACE 116=head1 FUNCTIONAL INTERFACE
125 117
126The following convenience methods are provided by this module. They are 118The following convenience methods are provided by this module. They are
127exported by default: 119exported by default:
148This function call is functionally identical to: 140This function call is functionally identical to:
149 141
150 $perl_scalar = JSON::XS->new->utf8->decode ($json_text) 142 $perl_scalar = JSON::XS->new->utf8->decode ($json_text)
151 143
152Except being faster. 144Except being faster.
153
154=item $is_boolean = JSON::XS::is_bool $scalar
155
156Returns true if the passed scalar represents either JSON::XS::true or
157JSON::XS::false, two constants that act like C<1> and C<0>, respectively
158and are used to represent JSON C<true> and C<false> values in Perl.
159
160See MAPPING, below, for more information on how JSON values are mapped to
161Perl.
162 145
163=back 146=back
164 147
165 148
166=head1 A FEW NOTES ON UNICODE AND PERL 149=head1 A FEW NOTES ON UNICODE AND PERL
667 650
668See SECURITY CONSIDERATIONS, below, for more info on why this is useful. 651See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
669 652
670=item $json_text = $json->encode ($perl_scalar) 653=item $json_text = $json->encode ($perl_scalar)
671 654
672Converts the given Perl data structure (a simple scalar or a reference 655Converts the given Perl value or data structure to its JSON
673to a hash or array) to its JSON representation. Simple scalars will be 656representation. Croaks on error.
674converted into JSON string or number sequences, while references to arrays
675become JSON arrays and references to hashes become JSON objects. Undefined
676Perl values (e.g. C<undef>) become JSON C<null> values. Neither C<true>
677nor C<false> values will be generated.
678 657
679=item $perl_scalar = $json->decode ($json_text) 658=item $perl_scalar = $json->decode ($json_text)
680 659
681The opposite of C<encode>: expects a JSON text and tries to parse it, 660The opposite of C<encode>: expects a JSON text and tries to parse it,
682returning the resulting simple scalar or reference. Croaks on error. 661returning the resulting simple scalar or reference. Croaks on error.
683
684JSON numbers and strings become simple Perl scalars. JSON arrays become
685Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
686C<1>, C<false> becomes C<0> and C<null> becomes C<undef>.
687 662
688=item ($perl_scalar, $characters) = $json->decode_prefix ($json_text) 663=item ($perl_scalar, $characters) = $json->decode_prefix ($json_text)
689 664
690This works like the C<decode> method, but instead of raising an exception 665This works like the C<decode> method, but instead of raising an exception
691when there is trailing garbage after the first JSON object, it will 666when there is trailing garbage after the first JSON object, it will
692silently stop parsing there and return the number of characters consumed 667silently stop parsing there and return the number of characters consumed
693so far. 668so far.
694 669
695This is useful if your JSON texts are not delimited by an outer protocol 670This is useful if your JSON texts are not delimited by an outer protocol
696(which is not the brightest thing to do in the first place) and you need
697to know where the JSON text ends. 671and you need to know where the JSON text ends.
698 672
699 JSON::XS->new->decode_prefix ("[1] the tail") 673 JSON::XS->new->decode_prefix ("[1] the tail")
700 => ([], 3) 674 => ([], 3)
701 675
702=back 676=back
741 715
742If the method is called in scalar context, then it will try to extract 716If the method is called in scalar context, then it will try to extract
743exactly I<one> JSON object. If that is successful, it will return this 717exactly I<one> JSON object. If that is successful, it will return this
744object, otherwise it will return C<undef>. If there is a parse error, 718object, otherwise it will return C<undef>. If there is a parse error,
745this method will croak just as C<decode> would do (one can then use 719this method will croak just as C<decode> would do (one can then use
746C<incr_skip> to skip the errornous part). This is the most common way of 720C<incr_skip> to skip the erroneous part). This is the most common way of
747using the method. 721using the method.
748 722
749And finally, in list context, it will try to extract as many objects 723And finally, in list context, it will try to extract as many objects
750from the stream as it can find and return them, or the empty list 724from the stream as it can find and return them, or the empty list
751otherwise. For this to work, there must be no separators between the JSON 725otherwise. For this to work, there must be no separators between the JSON
780C<incr_parse> died, in which case the input buffer and incremental parser 754C<incr_parse> died, in which case the input buffer and incremental parser
781state is left unchanged, to skip the text parsed so far and to reset the 755state is left unchanged, to skip the text parsed so far and to reset the
782parse state. 756parse state.
783 757
784The difference to C<incr_reset> is that only text until the parse error 758The difference to C<incr_reset> is that only text until the parse error
785occured is removed. 759occurred is removed.
786 760
787=item $json->incr_reset 761=item $json->incr_reset
788 762
789This completely resets the incremental parser, that is, after this call, 763This completely resets the incremental parser, that is, after this call,
790it will be as if the parser had never parsed anything. 764it will be as if the parser had never parsed anything.
796=back 770=back
797 771
798=head2 LIMITATIONS 772=head2 LIMITATIONS
799 773
800All options that affect decoding are supported, except 774All options that affect decoding are supported, except
801C<allow_nonref>. The reason for this is that it cannot be made to 775C<allow_nonref>. The reason for this is that it cannot be made to work
802work sensibly: JSON objects and arrays are self-delimited, i.e. you can concatenate 776sensibly: JSON objects and arrays are self-delimited, i.e. you can
803them back to back and still decode them perfectly. This does not hold true 777concatenate them back to back and still decode them perfectly. This does
804for JSON numbers, however. 778not hold true for JSON numbers, however.
805 779
806For example, is the string C<1> a single JSON number, or is it simply the 780For example, is the string C<1> a single JSON number, or is it simply the
807start of C<12>? Or is C<12> a single JSON number, or the concatenation 781start of C<12>? Or is C<12> a single JSON number, or the concatenation
808of C<1> and C<2>? In neither case you can tell, and this is why JSON::XS 782of C<1> and C<2>? In neither case you can tell, and this is why JSON::XS
809takes the conservative route and disallows this case. 783takes the conservative route and disallows this case.
988If the number consists of digits only, JSON::XS will try to represent 962If the number consists of digits only, JSON::XS will try to represent
989it as an integer value. If that fails, it will try to represent it as 963it as an integer value. If that fails, it will try to represent it as
990a numeric (floating point) value if that is possible without loss of 964a numeric (floating point) value if that is possible without loss of
991precision. Otherwise it will preserve the number as a string value (in 965precision. Otherwise it will preserve the number as a string value (in
992which case you lose roundtripping ability, as the JSON number will be 966which case you lose roundtripping ability, as the JSON number will be
993re-encoded toa JSON string). 967re-encoded to a JSON string).
994 968
995Numbers containing a fractional or exponential part will always be 969Numbers containing a fractional or exponential part will always be
996represented as numeric (floating point) values, possibly at a loss of 970represented as numeric (floating point) values, possibly at a loss of
997precision (in which case you might lose perfect roundtripping ability, but 971precision (in which case you might lose perfect roundtripping ability, but
998the JSON number will still be re-encoded as a JSON number). 972the JSON number will still be re-encoded as a JSON number).
999 973
1000Note that precision is not accuracy - binary floating point values cannot 974Note that precision is not accuracy - binary floating point values cannot
1001represent most decimal fractions exactly, and when converting from and to 975represent most decimal fractions exactly, and when converting from and to
1002floating point, JSON::XS only guarantees precision up to but not including 976floating point, JSON::XS only guarantees precision up to but not including
1003the leats significant bit. 977the least significant bit.
1004 978
1005=item true, false 979=item true, false
1006 980
1007These JSON atoms become C<JSON::XS::true> and C<JSON::XS::false>, 981These JSON atoms become C<Types::Serialiser::true> and
1008respectively. They are overloaded to act almost exactly like the numbers 982C<Types::Serialiser::false>, respectively. They are overloaded to act
1009C<1> and C<0>. You can check whether a scalar is a JSON boolean by using 983almost exactly like the numbers C<1> and C<0>. You can check whether
1010the C<JSON::XS::is_bool> function. 984a scalar is a JSON boolean by using the C<Types::Serialiser::is_bool>
985function (after C<use Types::Serialier>, of course).
1011 986
1012=item null 987=item null
1013 988
1014A JSON null atom becomes C<undef> in Perl. 989A JSON null atom becomes C<undef> in Perl.
1015 990
1024 999
1025=over 4 1000=over 4
1026 1001
1027=item hash references 1002=item hash references
1028 1003
1029Perl hash references become JSON objects. As there is no inherent ordering 1004Perl hash references become JSON objects. As there is no inherent
1030in hash keys (or JSON objects), they will usually be encoded in a 1005ordering in hash keys (or JSON objects), they will usually be encoded
1031pseudo-random order that can change between runs of the same program but 1006in a pseudo-random order. JSON::XS can optionally sort the hash keys
1032stays generally the same within a single run of a program. JSON::XS can 1007(determined by the I<canonical> flag), so the same datastructure will
1033optionally sort the hash keys (determined by the I<canonical> flag), so 1008serialise to the same JSON text (given same settings and version of
1034the same datastructure will serialise to the same JSON text (given same 1009JSON::XS), but this incurs a runtime overhead and is only rarely useful,
1035settings and version of JSON::XS), but this incurs a runtime overhead 1010e.g. when you want to compare some JSON text against another for equality.
1036and is only rarely useful, e.g. when you want to compare some JSON text
1037against another for equality.
1038 1011
1039=item array references 1012=item array references
1040 1013
1041Perl array references become JSON arrays. 1014Perl array references become JSON arrays.
1042 1015
1043=item other references 1016=item other references
1044 1017
1045Other unblessed references are generally not allowed and will cause an 1018Other unblessed references are generally not allowed and will cause an
1046exception to be thrown, except for references to the integers C<0> and 1019exception to be thrown, except for references to the integers C<0> and
1047C<1>, which get turned into C<false> and C<true> atoms in JSON. You can 1020C<1>, which get turned into C<false> and C<true> atoms in JSON.
1048also use C<JSON::XS::false> and C<JSON::XS::true> to improve readability.
1049 1021
1022Since C<JSON::XS> uses the boolean model from L<Types::Serialiser>, you
1023can also C<use Types::Serialiser> and then use C<Types::Serialiser::false>
1024and C<Types::Serialiser::true> to improve readability.
1025
1026 use Types::Serialiser;
1050 encode_json [\0, JSON::XS::true] # yields [false,true] 1027 encode_json [\0, Types::Serialiser::true] # yields [false,true]
1051 1028
1052=item JSON::XS::true, JSON::XS::false 1029=item Types::Serialiser::true, Types::Serialiser::false
1053 1030
1054These special values become JSON true and JSON false values, 1031These special values from the L<Types::Serialiser> module become JSON true
1055respectively. You can also use C<\1> and C<\0> directly if you want. 1032and JSON false values, respectively. You can also use C<\1> and C<\0>
1033directly if you want.
1056 1034
1057=item blessed objects 1035=item blessed objects
1058 1036
1059Blessed objects are not directly representable in JSON. See the 1037Blessed objects are not directly representable in JSON. See the
1060C<allow_blessed> and C<convert_blessed> methods on various options on 1038C<allow_blessed> and C<convert_blessed> methods on various options on
1138=item C<utf8> flag disabled 1116=item C<utf8> flag disabled
1139 1117
1140When C<utf8> is disabled (the default), then C<encode>/C<decode> generate 1118When C<utf8> is disabled (the default), then C<encode>/C<decode> generate
1141and expect Unicode strings, that is, characters with high ordinal Unicode 1119and expect Unicode strings, that is, characters with high ordinal Unicode
1142values (> 255) will be encoded as such characters, and likewise such 1120values (> 255) will be encoded as such characters, and likewise such
1143characters are decoded as-is, no canges to them will be done, except 1121characters are decoded as-is, no changes to them will be done, except
1144"(re-)interpreting" them as Unicode codepoints or Unicode characters, 1122"(re-)interpreting" them as Unicode codepoints or Unicode characters,
1145respectively (to Perl, these are the same thing in strings unless you do 1123respectively (to Perl, these are the same thing in strings unless you do
1146funny/weird/dumb stuff). 1124funny/weird/dumb stuff).
1147 1125
1148This is useful when you want to do the encoding yourself (e.g. when you 1126This is useful when you want to do the encoding yourself (e.g. when you
1264output for these property strings, e.g.: 1242output for these property strings, e.g.:
1265 1243
1266 $json =~ s/"__proto__"\s*:/"__proto__renamed":/g; 1244 $json =~ s/"__proto__"\s*:/"__proto__renamed":/g;
1267 1245
1268This works because C<__proto__> is not valid outside of strings, so every 1246This works because C<__proto__> is not valid outside of strings, so every
1269occurence of C<"__proto__"\s*:> must be a string used as property name. 1247occurrence of C<"__proto__"\s*:> must be a string used as property name.
1270 1248
1271If you know of other incompatibilities, please let me know. 1249If you know of other incompatibilities, please let me know.
1272 1250
1273 1251
1274=head2 JSON and YAML 1252=head2 JSON and YAML
1436are browser design bugs, but it is still you who will have to deal with 1414are browser design bugs, but it is still you who will have to deal with
1437it, as major browser developers care only for features, not about getting 1415it, as major browser developers care only for features, not about getting
1438security right). 1416security right).
1439 1417
1440 1418
1419=head1 INTEROPERABILITY WITH OTHER MODULES
1420
1421C<JSON::XS> uses the L<Types::Serialiser> module to provide boolean
1422constants. That means that the JSON true and false values will be
1423comaptible to true and false values of iother modules that do the same,
1424such as L<JSON::PP> and L<CBOR::XS>.
1425
1426
1441=head1 THREADS 1427=head1 THREADS
1442 1428
1443This module is I<not> guaranteed to be thread safe and there are no 1429This module is I<not> guaranteed to be thread safe and there are no
1444plans to change this until Perl gets thread support (as opposed to the 1430plans to change this until Perl gets thread support (as opposed to the
1445horribly slow so-called "threads" which are simply slow and bloated 1431horribly slow so-called "threads" which are simply slow and bloated
1452 1438
1453Sometimes people avoid the Perl locale support and directly call the 1439Sometimes people avoid the Perl locale support and directly call the
1454system's setlocale function with C<LC_ALL>. 1440system's setlocale function with C<LC_ALL>.
1455 1441
1456This breaks both perl and modules such as JSON::XS, as stringification of 1442This breaks both perl and modules such as JSON::XS, as stringification of
1457numbers no longer works correcly (e.g. C<$x = 0.1; print "$x"+1> might 1443numbers no longer works correctly (e.g. C<$x = 0.1; print "$x"+1> might
1458print C<1>, and JSON::XS might output illegal JSON as JSON::XS relies on 1444print C<1>, and JSON::XS might output illegal JSON as JSON::XS relies on
1459perl to stringify numbers). 1445perl to stringify numbers).
1460 1446
1461The solution is simple: don't call C<setlocale>, or use it for only those 1447The solution is simple: don't call C<setlocale>, or use it for only those
1462categories you need, such as C<LC_MESSAGES> or C<LC_CTYPE>. 1448categories you need, such as C<LC_MESSAGES> or C<LC_CTYPE>.
1475Please refrain from using rt.cpan.org or any other bug reporting 1461Please refrain from using rt.cpan.org or any other bug reporting
1476service. I put the contact address into my modules for a reason. 1462service. I put the contact address into my modules for a reason.
1477 1463
1478=cut 1464=cut
1479 1465
1480our $true = do { bless \(my $dummy = 1), "JSON::XS::Boolean" }; 1466BEGIN {
1481our $false = do { bless \(my $dummy = 0), "JSON::XS::Boolean" }; 1467 *true = \$Types::Serialiser::true;
1468 *true = \&Types::Serialiser::true;
1469 *false = \$Types::Serialiser::false;
1470 *false = \&Types::Serialiser::false;
1471 *is_bool = \&Types::Serialiser::is_bool;
1482 1472
1483sub true() { $true } 1473 *JSON::XS::Boolean:: = *Types::Serialiser::Boolean::;
1484sub false() { $false }
1485
1486sub is_bool($) {
1487 UNIVERSAL::isa $_[0], "JSON::XS::Boolean"
1488# or UNIVERSAL::isa $_[0], "JSON::Literal"
1489} 1474}
1490 1475
1491XSLoader::load "JSON::XS", $VERSION; 1476XSLoader::load "JSON::XS", $VERSION;
1492
1493package JSON::XS::Boolean;
1494
1495use overload
1496 "0+" => sub { ${$_[0]} },
1497 "++" => sub { $_[0] = ${$_[0]} + 1 },
1498 "--" => sub { $_[0] = ${$_[0]} - 1 },
1499 fallback => 1;
1500
15011;
1502 1477
1503=head1 SEE ALSO 1478=head1 SEE ALSO
1504 1479
1505The F<json_xs> command line utility for quick experiments. 1480The F<json_xs> command line utility for quick experiments.
1506 1481
1509 Marc Lehmann <schmorp@schmorp.de> 1484 Marc Lehmann <schmorp@schmorp.de>
1510 http://home.schmorp.de/ 1485 http://home.schmorp.de/
1511 1486
1512=cut 1487=cut
1513 1488
14891
1490

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines