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.84 by root, Wed Mar 19 02:52:15 2008 UTC vs.
Revision 1.91 by root, Thu Mar 20 02:11:21 2008 UTC

103 103
104package JSON::XS; 104package JSON::XS;
105 105
106use strict; 106use strict;
107 107
108our $VERSION = '2.01'; 108our $VERSION = '2.1';
109our @ISA = qw(Exporter); 109our @ISA = qw(Exporter);
110 110
111our @EXPORT = qw(encode_json decode_json to_json from_json); 111our @EXPORT = qw(encode_json decode_json to_json from_json);
112 112
113sub to_json($) { 113sub to_json($) {
245 245
246If C<$enable> is false, then the C<encode> method will not escape Unicode 246If C<$enable> is false, then the C<encode> method will not escape Unicode
247characters unless required by the JSON syntax or other flags. This results 247characters unless required by the JSON syntax or other flags. This results
248in a faster and more compact format. 248in a faster and more compact format.
249 249
250See also the section I<ENCODING/CODESET FLAG NOTES> later in this
251document.
252
250The main use for this flag is to produce JSON texts that can be 253The main use for this flag is to produce JSON texts that can be
251transmitted over a 7-bit channel, as the encoded JSON texts will not 254transmitted over a 7-bit channel, as the encoded JSON texts will not
252contain any 8 bit characters. 255contain any 8 bit characters.
253 256
254 JSON::XS->new->ascii (1)->encode ([chr 0x10401]) 257 JSON::XS->new->ascii (1)->encode ([chr 0x10401])
265will not be affected in any way by this flag, as C<decode> by default 268will not be affected in any way by this flag, as C<decode> by default
266expects Unicode, which is a strict superset of latin1. 269expects Unicode, which is a strict superset of latin1.
267 270
268If C<$enable> is false, then the C<encode> method will not escape Unicode 271If C<$enable> is false, then the C<encode> method will not escape Unicode
269characters unless required by the JSON syntax or other flags. 272characters unless required by the JSON syntax or other flags.
273
274See also the section I<ENCODING/CODESET FLAG NOTES> later in this
275document.
270 276
271The main use for this flag is efficiently encoding binary data as JSON 277The main use for this flag is efficiently encoding binary data as JSON
272text, as most octets will not be escaped, resulting in a smaller encoded 278text, as most octets will not be escaped, resulting in a smaller encoded
273size. The disadvantage is that the resulting JSON text is encoded 279size. The disadvantage is that the resulting JSON text is encoded
274in latin1 (and must correctly be treated as such when storing and 280in latin1 (and must correctly be treated as such when storing and
293 299
294If C<$enable> is false, then the C<encode> method will return the JSON 300If C<$enable> is false, then the C<encode> method will return the JSON
295string as a (non-encoded) Unicode string, while C<decode> expects thus a 301string as a (non-encoded) Unicode string, while C<decode> expects thus a
296Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs 302Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs
297to be done yourself, e.g. using the Encode module. 303to be done yourself, e.g. using the Encode module.
304
305See also the section I<ENCODING/CODESET FLAG NOTES> later in this
306document.
298 307
299Example, output UTF-16BE-encoded JSON: 308Example, output UTF-16BE-encoded JSON:
300 309
301 use Encode; 310 use Encode;
302 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); 311 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
816 my $x = "3"; # some variable containing a string 825 my $x = "3"; # some variable containing a string
817 $x += 0; # numify it, ensuring it will be dumped as a number 826 $x += 0; # numify it, ensuring it will be dumped as a number
818 $x *= 1; # same thing, the choice is yours. 827 $x *= 1; # same thing, the choice is yours.
819 828
820You can not currently force the type in other, less obscure, ways. Tell me 829You can not currently force the type in other, less obscure, ways. Tell me
821if you need this capability (but don't forget to explain why its needed 830if you need this capability (but don't forget to explain why it's needed
822:). 831:).
823 832
824=back 833=back
825 834
826 835
828 837
829The interested reader might have seen a number of flags that signify 838The interested reader might have seen a number of flags that signify
830encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be 839encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be
831some confusion on what these do, so here is a short comparison: 840some confusion on what these do, so here is a short comparison:
832 841
833C<utf8> controls wether the JSON text created by C<encode> (and expected 842C<utf8> controls whether the JSON text created by C<encode> (and expected
834by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only 843by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only
835control wether C<encode> escapes character values outside their respective 844control whether C<encode> escapes character values outside their respective
836codeset range. Neither of these flags conflict with each other, although 845codeset range. Neither of these flags conflict with each other, although
837some combinations make less sense than others. 846some combinations make less sense than others.
838 847
839Care has been taken to make all flags symmetrical with respect to 848Care has been taken to make all flags symmetrical with respect to
840C<encode> and C<decode>, that is, texts encoded with any combination of 849C<encode> and C<decode>, that is, texts encoded with any combination of
938directly when available (so will be 100% compatible with it, including 947directly when available (so will be 100% compatible with it, including
939speed), or it uses JSON::PP, which is basically JSON::XS translated to 948speed), or it uses JSON::PP, which is basically JSON::XS translated to
940Pure Perl, which should be 100% compatible with JSON::XS, just a bit 949Pure Perl, which should be 100% compatible with JSON::XS, just a bit
941slower. 950slower.
942 951
943You cannot really lose by using this module. 952You cannot really lose by using this module, especially as it tries very
953hard to work even with ancient Perl versions, while JSON::XS does not.
944 954
945=item JSON 1.07 955=item JSON 1.07
946 956
947Slow (but very portable, as it is written in pure Perl). 957Slow (but very portable, as it is written in pure Perl).
948 958
1020 1030
1021 1031
1022=head2 JSON and YAML 1032=head2 JSON and YAML
1023 1033
1024You often hear that JSON is a subset of YAML. This is, however, a mass 1034You often hear that JSON is a subset of YAML. This is, however, a mass
1025hysteria(*) and very far from the truth. In general, there is no way to 1035hysteria(*) and very far from the truth (as of the time of this writing),
1036so let me state it clearly: I<in general, there is no way to configure
1026configure JSON::XS to output a data structure as valid YAML that works for 1037JSON::XS to output a data structure as valid YAML> that works in all
1027all cases. 1038cases.
1028 1039
1029If you really must use JSON::XS to generate YAML, you should use this 1040If you really must use JSON::XS to generate YAML, you should use this
1030algorithm (subject to change in future versions): 1041algorithm (subject to change in future versions):
1031 1042
1032 my $to_yaml = JSON::XS->new->utf8->space_after (1); 1043 my $to_yaml = JSON::XS->new->utf8->space_after (1);
1035This will I<usually> generate JSON texts that also parse as valid 1046This will I<usually> generate JSON texts that also parse as valid
1036YAML. Please note that YAML has hardcoded limits on (simple) object key 1047YAML. Please note that YAML has hardcoded limits on (simple) object key
1037lengths that JSON doesn't have and also has different and incompatible 1048lengths that JSON doesn't have and also has different and incompatible
1038unicode handling, so you should make sure that your hash keys are 1049unicode handling, so you should make sure that your hash keys are
1039noticeably shorter than the 1024 "stream characters" YAML allows and that 1050noticeably shorter than the 1024 "stream characters" YAML allows and that
1040you do not have codepoints with values outside the Unicode BMP (basic 1051you do not have characters with codepoint values outside the Unicode BMP
1041multilingual page). YAML also does not allow C<\/> sequences in strings 1052(basic multilingual page). YAML also does not allow C<\/> sequences in
1042(which JSON::XS does not I<currently> generate). 1053strings (which JSON::XS does not I<currently> generate, but other JSON
1054generators might).
1043 1055
1044There might be other incompatibilities that I am not aware of (or the YAML 1056There might be other incompatibilities that I am not aware of (or the YAML
1045specification has been changed yet again - it does so quite often). In 1057specification has been changed yet again - it does so quite often). In
1046general you should not try to generate YAML with a JSON generator or vice 1058general you should not try to generate YAML with a JSON generator or vice
1047versa, or try to parse JSON with a YAML parser or vice versa: chances are 1059versa, or try to parse JSON with a YAML parser or vice versa: chances are
1050 1062
1051=over 4 1063=over 4
1052 1064
1053=item (*) 1065=item (*)
1054 1066
1055This is spread actively by the YAML team, however. For many years now they 1067I have been pressured multiple times by Brian Ingerson (one of the
1056claim YAML were a superset of JSON, even when proven otherwise. 1068authors of the YAML specification) to remove this paragraph, despite him
1069acknowledging that the actual incompatibilities exist. As I was personally
1070bitten by this "JSON is YAML" lie, I refused and said I will continue to
1071educate people about these issues, so others do not run into the same
1072problem again and again. After this, Brian called me a (quote)I<complete
1073and worthless idiot>(unquote).
1057 1074
1058Even the author of this manpage was at some point accused of providing 1075In my opinion, instead of pressuring and insulting people who actually
1059"incorrect" information, despite the evidence presented (claims ranged 1076clarify issues with YAML and the wrong statements of some of its
1060from "your documentation contains inaccurate and negative statements about 1077proponents, I would kindly suggest reading the JSON spec (which is not
1061YAML" (the only negative comment is this footnote, and it didn't exist 1078that difficult or long) and finally make YAML compatible to it, and
1062back then; the question on which claims were inaccurate was never answered 1079educating users about the changes, instead of spreading lies about the
1063etc.) to "the YAML spec is not up-to-date" (the *real* and supposedly 1080real compatibility for many I<years> and trying to silence people who
1064JSON-compatible spec is apparently not currently publicly available) 1081point out that it isn't true.
1065to actual requests to replace this section by *incorrect* information,
1066suppressing information about the real problem).
1067
1068So whenever you are told that YAML was a superset of JSON, first check
1069wether it is really true (it might be when you check it, but it certainly
1070was not true when this was written). I would much prefer if the YAML team
1071would spent their time on actually making JSON compatibility a truth
1072(JSON, after all, has a very small and simple specification) instead of
1073trying to lobby/force people into reporting untruths.
1074 1082
1075=back 1083=back
1076 1084
1077 1085
1078=head2 SPEED 1086=head2 SPEED
1080It seems that JSON::XS is surprisingly fast, as shown in the following 1088It seems that JSON::XS is surprisingly fast, as shown in the following
1081tables. They have been generated with the help of the C<eg/bench> program 1089tables. They have been generated with the help of the C<eg/bench> program
1082in the JSON::XS distribution, to make it easy to compare on your own 1090in the JSON::XS distribution, to make it easy to compare on your own
1083system. 1091system.
1084 1092
1085First comes a comparison between various modules using a very short 1093First comes a comparison between various modules using
1086single-line JSON string: 1094a very short single-line JSON string (also available at
1095L<http://dist.schmorp.de/misc/json/short.json>).
1087 1096
1088 {"method": "handleMessage", "params": ["user1", "we were just talking"], \ 1097 {"method": "handleMessage", "params": ["user1", "we were just talking"], \
1089 "id": null, "array":[1,11,234,-5,1e5,1e7, true, false]} 1098 "id": null, "array":[1,11,234,-5,1e5,1e7, true, false]}
1090 1099
1091It shows the number of encodes/decodes per second (JSON::XS uses 1100It shows the number of encodes/decodes per second (JSON::XS uses
1110about three times faster on decoding, and over forty times faster 1119about three times faster on decoding, and over forty times faster
1111than JSON, even with pretty-printing and key sorting. It also compares 1120than JSON, even with pretty-printing and key sorting. It also compares
1112favourably to Storable for small amounts of data. 1121favourably to Storable for small amounts of data.
1113 1122
1114Using a longer test string (roughly 18KB, generated from Yahoo! Locals 1123Using a longer test string (roughly 18KB, generated from Yahoo! Locals
1115search API (http://nanoref.com/yahooapis/mgPdGg): 1124search API (L<http://dist.schmorp.de/misc/json/long.json>).
1116 1125
1117 module | encode | decode | 1126 module | encode | decode |
1118 -----------|------------|------------| 1127 -----------|------------|------------|
1119 JSON 1.x | 55.260 | 34.971 | 1128 JSON 1.x | 55.260 | 34.971 |
1120 JSON::DWIW | 825.228 | 1082.513 | 1129 JSON::DWIW | 825.228 | 1082.513 |
1162to free the temporary). If that is exceeded, the program crashes. To be 1171to free the temporary). If that is exceeded, the program crashes. To be
1163conservative, the default nesting limit is set to 512. If your process 1172conservative, the default nesting limit is set to 512. If your process
1164has a smaller stack, you should adjust this setting accordingly with the 1173has a smaller stack, you should adjust this setting accordingly with the
1165C<max_depth> method. 1174C<max_depth> method.
1166 1175
1167And last but least, something else could bomb you that I forgot to think 1176Something else could bomb you, too, that I forgot to think of. In that
1168of. In that case, you get to keep the pieces. I am always open for hints, 1177case, you get to keep the pieces. I am always open for hints, though...
1169though... 1178
1179Also keep in mind that JSON::XS might leak contents of your Perl data
1180structures in its error messages, so when you serialise sensitive
1181information you might want to make sure that exceptions thrown by JSON::XS
1182will not end up in front of untrusted eyes.
1170 1183
1171If you are using JSON::XS to return packets to consumption 1184If you are using JSON::XS to return packets to consumption
1172by JavaScript scripts in a browser you should have a look at 1185by JavaScript scripts in a browser you should have a look at
1173L<http://jpsykes.com/47/practical-csrf-and-json-security> to see whether 1186L<http://jpsykes.com/47/practical-csrf-and-json-security> to see whether
1174you are vulnerable to some common attack vectors (which really are browser 1187you are vulnerable to some common attack vectors (which really are browser
1180=head1 THREADS 1193=head1 THREADS
1181 1194
1182This module is I<not> guaranteed to be thread safe and there are no 1195This module is I<not> guaranteed to be thread safe and there are no
1183plans to change this until Perl gets thread support (as opposed to the 1196plans to change this until Perl gets thread support (as opposed to the
1184horribly slow so-called "threads" which are simply slow and bloated 1197horribly slow so-called "threads" which are simply slow and bloated
1185process simulations - use fork, its I<much> faster, cheaper, better). 1198process simulations - use fork, it's I<much> faster, cheaper, better).
1186 1199
1187(It might actually work, but you have been warned). 1200(It might actually work, but you have been warned).
1188 1201
1189 1202
1190=head1 BUGS 1203=head1 BUGS
1191 1204
1192While the goal of this module is to be correct, that unfortunately does 1205While the goal of this module is to be correct, that unfortunately does
1193not mean its bug-free, only that I think its design is bug-free. It is 1206not mean it's bug-free, only that I think its design is bug-free. It is
1194still relatively early in its development. If you keep reporting bugs they 1207still relatively early in its development. If you keep reporting bugs they
1195will be fixed swiftly, though. 1208will be fixed swiftly, though.
1196 1209
1197Please refrain from using rt.cpan.org or any other bug reporting 1210Please refrain from using rt.cpan.org or any other bug reporting
1198service. I put the contact address into my modules for a reason. 1211service. I put the contact address into my modules for a reason.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines