|
NAMEJSON::Parse - Parse JSONSYNOPSISuse JSON::Parse 'parse_json'; my $json = '["golden", "fleece"]'; my $perl = parse_json ($json); # Same effect as $perl = ['golden', 'fleece']; Convert JSON into Perl. VERSIONThis documents version 0.61 of JSON::Parse corresponding to git commit 033269fa8972fdce8626aa65cd11a5394ab50492 <https://github.com/benkasminbullock/JSON-Parse/commit/033269fa8972fdce8626aa65cd11a5394ab50492> released on Thu Feb 11 09:14:04 2021 +0900.DESCRIPTIONA module for parsing JSON. (JSON means "JavaScript Object Notation" and it is specified in "RFC 8259".)JSON::Parse offers the function "parse_json", which takes a string containing JSON, and returns an equivalent Perl structure. It also offers validation of JSON via "valid_json", which returns true or false depending on whether the JSON is correct or not, and "assert_valid_json", which produces a descriptive fatal error if the JSON is invalid. A function "read_json" reads JSON from a file, and there is a safer version of "parse_json" called "parse_json_safe" which doesn't throw exceptions. For special cases of parsing, there are also methods "new" and "parse", which create a JSON parsing object and run it on text. See "METHODS". JSON::Parse accepts only UTF-8 as input. See "UTF-8 only" and "Handling of Unicode". FUNCTIONSassert_valid_jsonuse JSON::Parse 'assert_valid_json'; eval { assert_valid_json ('["xyz":"b"]'); }; if ($@) { print "Your JSON was invalid: $@\n"; } # Prints "Unexpected character ':' parsing array" produces output Your JSON was invalid: JSON error at line 1, byte 7/11: Unexpected character ':' parsing array starting from byte 1: expecting whitespace: 'n', '\r', '\t', ' ' or comma: ',' or end of array: ']' at /usr/home/ben/projects/json-parse/examples/assert.pl line 6. (This example is included as assert.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/assert.pl> in the distribution.) This is the underlying function for "valid_json". It runs at the same speed, but it throws an error if the JSON is wrong, rather than returning 1 or 0. See "DIAGNOSTICS" for the error format, which is identical to "parse_json". This cannot detect key collisions in the JSON since it does not store values. See "Key collisions" for more on this module's handling of non-unique names in the JSON. The method equivalent to this is "check". The behaviour of disallowing empty inputs was changed in version 0.49. parse_jsonuse JSON::Parse 'parse_json'; my $perl = parse_json ('{"x":1, "y":2}'); This function converts JSON into a Perl structure, either an array reference, a hash reference, or a scalar. If the first argument does not contain a complete valid JSON text, is the undefined value, an empty string, or a string containing only whitespace "parse_json" throws a fatal error ("dies"). If the argument contains valid JSON, the return value is either a hash reference, an array reference, or a scalar. If the input JSON text is a serialized object, a hash reference is returned: use JSON::Parse ':all'; my $perl = parse_json ('{"a":1, "b":2}'); print ref $perl, "\n"; produces output HASH (This example is included as hash.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/hash.pl> in the distribution.) If the input JSON text is a serialized array, an array reference is returned: use JSON::Parse ':all'; my $perl = parse_json ('["a", "b", "c"]'); print ref $perl, "\n"; produces output ARRAY (This example is included as array.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/array.pl> in the distribution.) Otherwise a Perl scalar is returned. The behaviour of allowing a scalar was added in version 0.32 of this module. This brings it into line with the new specification for JSON. The behaviour of disallowing empty inputs was changed in version 0.49. The function "parse_json_safe" offers a version of this function with various safety features enabled. The method "parse" is equivalent to this. parse_json_safeThis is almost the same thing as "parse_json", but has the following differences:
As the name implies, this is meant to be a "safety-first" version of "parse_json". 🎲 This function was added in version 0.38. read_jsonuse JSON::Parse 'read_json'; my $p = read_json ('filename'); This is exactly the same as "parse_json" except that it reads the JSON from the specified file rather than a scalar. The file must be in the UTF-8 encoding, and is opened as a character file using ":encoding(utf8)" (see PerlIO::encoding and perluniintro). The output is marked as character strings. The method equivalent is "read". This is a convenience function written in Perl. You may prefer to read the file yourself using another module if you need faster performance. This was renamed from "json_file_to_perl" in version 0.59. The old name will also continue to work indefinitely. valid_jsonuse JSON::Parse 'valid_json'; if (valid_json ($json)) { # do something } "valid_json" returns 1 if its argument is valid JSON and 0 if not. It runs several times faster than "parse_json". This gain in speed is obtained because it discards the input data after reading it, rather than storing it into Perl variables. This does not supply the actual errors which caused invalidity. Use "assert_valid_json" to get error messages when the JSON is invalid. This cannot detect duplicate keys in JSON objects because it does not store values. See "Key collisions" for more on this module's handling of non-unique names in the JSON. METHODSIf you need to parse JSON and you are not satisfied with the parsing options offered by "parse_json" and "parse_json_safe", you can create a JSON parsing object with "new" and set various options on the object, then use it with "parse" or "read".There are options to copy JSON literals ("true", "false", "null") with "copy_literals", switch off fatal errors with "warn_only", detect duplicate keys in objects with "detect_collisions", set the maximum depth of nested objects and arrays with "set_max_depth", produce machine-readable parsing errors with "diagnostics_hash", and set the JSON literals to user defined values with the methods described under "Methods for manipulating literals". These methods only affect the object created with "new"; they do not globally affect the behaviour of "parse_json" or "parse_json_safe". checkeval { $jp->check ($json); }; This does the same thing as "assert_valid_json", except its behaviour can be modified using the "diagnostics_hash" method. 🎲 This method was added in version 0.48. This is for the benefit of JSON::Repair. copy_literals$jp->copy_literals (1); With a true value, copy JSON literal values ("null", "true", and "false") into new Perl scalar values, and don't put read-only values into the output. With a false value, use read-only scalars: $jp->copy_literals (0); The "copy_literals (1)" behaviour is the behaviour of "parse_json_safe". The "copy_literals (0)" behaviour is the behaviour of "parse_json". If the user also sets user-defined literals with "set_true", "set_false" and "set_null", that takes precedence over this. 🎲 This method was added in version 0.38. detect_collisions$jp->detect_collisions (1); This switches on a check for hash key collisions (non-unique names in JSON objects). If a collision is found, an error message "Name is not unique" is printed, which also gives the non-unique name and the byte position where the start of the colliding string was found: use JSON::Parse; my $jp = JSON::Parse->new (); $jp->detect_collisions (1); eval { $jp->parse ('{"animals":{"cat":"moggy","cat":"feline","cat":"neko"}}'); }; print "$@\n" if $@; produces output JSON error at line 1, byte 28/55: Name is not unique: "cat" parsing object starting from byte 12 at /usr/home/ben/projects/json-parse/examples/../blib/lib/JSON/Parse.pm line 131. (This example is included as collide.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/collide.pl> in the distribution.) The "detect_collisions (1)" behaviour is the behaviour of "parse_json_safe". The "detect_collisions (0)" behaviour is the behaviour of "parse_json". 🎲 This method was added in version 0.38. diagnostics_hash$jp->diagnostics_hash (1); This changes diagnostics produced by errors from a simple string into a hash reference containing various fields. This is incompatible with "warn_only". This replaces the previous experimental global variable $json_diagnostics, which was removed from the module. The hash keys and values are identical to those provided in the object returned by $json_diagnostics, with the addition of a key "error as string" which returns the usual error. This requires Perl version 5.14 or later. An example of the use of this method to "repair" broken JSON is in the module "JSON::Repair". 🎲 This method was added in version 0.46. get_max_depthmy $max_depth = $jp->get_max_depth (); This returns the maximum nesting depth of objects or arrays in the input JSON. The default value is 10,000. 🎲 This method was added in version 0.58. newmy $jp = JSON::Parse->new (); Create a new JSON::Parse object. 🎲 This method was added in version 0.38. parsemy $out = $jp->parse ($json); This does the same thing as "parse_json", except its behaviour can be modified using object methods. 🎲 This method was added in version 0.38. This was renamed from "run" in version 0.60. readmy $json = $jp->read ($file); Read a file, parse the contained JSON, and return the output. This method is equivalent to the function "read_json". 🎲 This method was added in version 0.60. set_max_depth$jp->set_max_depth (42); Set the maximum nesting depth of objects or arrays in the input JSON. The default value is 10,000. 🎲 This method was added in version 0.58. upgrade_utf8$jp->upgrade_utf8 (1); Upgrade input from bytes to characters automatically. This can be switched off again using any false value: $jp->upgrade_utf8 (0); 🎲 This method was added in version 0.61. warn_only$jp->warn_only (1); Warn, don't die, on error. Failed parsing returns the undefined value, "undef", and prints a warning. This can be switched off again using any false value: $jp->warn_only (''); 🎲 This method was added in version 0.41. Methods for manipulating literalsThese methods alter what is written into the Perl structure when the parser sees a literal value, "true", "false" or "null" in the input JSON.This number of methods is needed because of the possibility that a user wants to set the output for "false" to be "undef": $jp->set_false (undef); Thus, we cannot use a single function "$jp->false (undef)" to cover both setting and deleting of values. 🎲 This facility was added in version 0.38. set_true $jp->set_true ("Yes, that is so true"); Supply a scalar to be used in place of the JSON "true" literal. This example puts the string "Yes, that is so true" into the hash or array when we hit a "true" literal, rather than the default read-only scalar: use JSON::Parse; my $json = '{"yes":true,"no":false}'; my $jp = JSON::Parse->new (); $jp->set_true ('Yes, that is so true'); my $out = $jp->parse ($json); print $out->{yes}, "\n"; prints Yes, that is so true To override the previous value, call it again with a new value. To delete the value and revert to the default behaviour, use "delete_true". If you give this a value which is not "true", as in Perl will evaluate it as a false in an if statement, it prints a warning "User-defined value for JSON true evaluates as false". You can switch this warning off with "no_warn_literals". 🎲 This method was added in version 0.38. delete_true $jp->delete_true (); Delete the user-defined true value. See "set_true". This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value. 🎲 This method was added in version 0.38. set_false $jp->set_false (JSON::PP::Boolean::false); Supply a scalar to be used in place of the JSON "false" literal. In the above example, when we hit a "false" literal, we put "JSON::PP::Boolean::false" in the output, similar to JSON::PP and other CPAN modules like Mojo::JSON or JSON::XS. To override the previous value, call it again with a new value. To delete the value and revert to the default behaviour, use "delete_false". If you give this a value which is not "false", as in Perl will evaluate it as a false in an if statement, it prints a warning "User-defined value for JSON false evaluates as true". You can switch this warning off with "no_warn_literals". 🎲 This method was added in version 0.38. delete_false $jp->delete_false (); Delete the user-defined false value. See "set_false". This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value. 🎲 This method was added in version 0.38. set_null $jp->set_null (0); Supply a scalar to be used in place of the JSON "null" literal. To override the previous value, call it again with a new value. To delete the value and revert to the default behaviour, use "delete_null". 🎲 This method was added in version 0.38. delete_null $jp->delete_null (); Delete the user-defined null value. See "set_null". This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value. 🎲 This method was added in version 0.38. no_warn_literals $jp->no_warn_literals (1); Use a true value to switch off warnings about setting boolean values to contradictory things. For example if you want to set the JSON "false" literal to turn into the string "false", $jp->no_warn_literals (1); $jp->set_false ("false"); See also "Contradictory values for "true" and "false"". This also switches off the warning "User-defined value overrules copy_literals". 🎲 This method was added in version 0.38. OLD INTERFACEThe following alternative function names are accepted. These are the names used for the functions in old versions of this module. These names are not deprecated and will never be removed from the module.The names ending in "_to_perl" seem quite silly in retrospect since surely it is obvious that one is programming in Perl. json_to_perlThis is exactly the same function as "parse_json".json_file_to_perlThis is exactly the same function as "read_json". The function was renamed in version 0.59, after the same function in "File::JSON::Slurper".runThis is the old name for "parse".validate_jsonThis is exactly the same function as "assert_valid_json".Mapping from JSON to PerlJSON elements are mapped to Perl as follows:JSON numbersJSON numbers become Perl numbers, either integers or double-precision floating point numbers, or possibly strings containing the number if parsing of a number by the usual methods fails somehow.JSON does not allow leading zeros, like 0123, or leading plus signs, like +100, in numbers, so these cause an "Unexpected character" error. JSON also does not allow numbers of the form 1., but it does allow things like 0e0 or 1E999999. As far as possible these are accepted by JSON::Parse. JSON stringsJSON strings become Perl strings. The JSON escape characters such as "\t" for the tab character (see section 2.5 of "RFC 8259") are mapped to the equivalent ASCII character.Handling of Unicode Inputs must be in the UTF-8 format. See "UTF-8 only". In addition, JSON::Parse rejects UTF-8 which encodes non-characters such as "U+FFFF" and ill-formed characters such as incomplete halves of surrogate pairs. Unicode encoding points in the input of the form "\u3000" are converted into the equivalent UTF-8 bytes. Surrogate pairs in the form "\uD834\uDD1E" are also handled. If the second half of the surrogate pair is missing, an "Unexpected character" or "Unexpected end of input" error is thrown. If the second half of the surrogate pair is present but contains an impossible value, a "Not surrogate pair" error is thrown. If the input to "parse_json" is marked as Unicode characters, the output strings will be marked as Unicode characters. If the input is not marked as Unicode characters, the output strings will not be marked as Unicode characters. Thus, use JSON::Parse ':all'; # The scalar $sasori looks like Unicode to Perl use utf8; my $sasori = '["蠍"]'; my $p = parse_json ($sasori); print utf8::is_utf8 ($p->[0]); # Prints 1. but use JSON::Parse ':all'; # The scalar $ebi does not look like Unicode to Perl no utf8; my $ebi = '["海老"]'; my $p = parse_json ($ebi); print utf8::is_utf8 ($p->[0]); # Prints nothing. Escapes of the form \uXXXX (see page three of "RFC 8259") are mapped to ASCII if XXXX is less than 0x80, or to UTF-8 if XXXX is greater than or equal to 0x80. Strings containing \uXXXX escapes greater than 0x80 are also upgraded to character strings, regardless of whether the input is a character string or a byte string, thus regardless of whether Perl thinks the input string is Unicode, escapes like \u87f9 are converted into the equivalent UTF-8 bytes and the particular string in which they occur is marked as a character string: use JSON::Parse ':all'; no utf8; # 蟹 my $kani = '["\u87f9"]'; my $p = parse_json ($kani); print "It's marked as a character string" if utf8::is_utf8 ($p->[0]); # Prints "It's marked as a character string" because it's upgraded # regardless of the input string's flags. This is modelled on the behaviour of Perl's "chr": no utf8; my $kani = '87f9'; print "hex is character string\n" if utf8::is_utf8 ($kani); # prints nothing $kani = chr (hex ($kani)); print "chr makes it a character string\n" if utf8::is_utf8 ($kani); # prints "chr makes it a character string" However, JSON::Parse also upgrades the remaining part of the string into a character string, even when it's not marked as a character string. For example, use JSON::Parse ':all'; use Unicode::UTF8 'decode_utf8'; no utf8; my $highbytes = "か"; my $not_utf8 = "$highbytes\\u3042"; my $test = "{\"a\":\"$not_utf8\"}"; my $out = parse_json ($test); # JSON::Parse does something unusual here in promoting the first part # of the string into UTF-8. print "JSON::Parse gives this: ", $out->{a}, "\n"; # Perl cannot assume that $highbytes is in UTF-8, so it has to just # turn the initial characters into garbage. my $add_chr = $highbytes . chr (0x3042); print "Perl's output is like this: ", $add_chr, "\n"; # In fact JSON::Parse's behaviour is equivalent to this: my $equiv = decode_utf8 ($highbytes) . chr (0x3042); print "JSON::Parse did something like this: ", $equiv, "\n"; # With character strings switched on, Perl and JSON::Parse do the same # thing. use utf8; my $is_utf8 = "か"; my $test2 = "{\"a\":\"$is_utf8\\u3042\"}"; my $out2 = parse_json ($test2); print "JSON::Parse: ", $out2->{a}, "\n"; my $add_chr2 = $is_utf8 . chr (0x3042); print "Native Perl: ", $add_chr2, "\n"; produces output JSON::Parse gives this: かあ Perl's output is like this: ã��あ JSON::Parse did something like this: かあ JSON::Parse: かあ Native Perl: かあ (This example is included as unicode-details.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/unicode-details.pl> in the distribution.) Although in general the above would be an unsafe practice, JSON::Parse can do things this way because JSON is a text-only, Unicode-only format. To ensure that invalid inputs are never upgraded, JSON::Parse checks each input byte to make sure that it forms UTF-8. See also "UTF-8 only". Doing things this way, rather than the way that Perl does it, was one of the original motivations for writing this module. JSON arraysJSON arrays become Perl array references. The elements of the Perl array are in the same order as they appear in the JSON.Thus my $p = parse_json ('["monday", "tuesday", "wednesday"]'); has the same result as a Perl declaration of the form my $p = [ 'monday', 'tuesday', 'wednesday' ]; JSON objectsJSON objects become Perl hashes. The members of the JSON object become key and value pairs in the Perl hash. The string part of each object member becomes the key of the Perl hash. The value part of each member is mapped to the value of the Perl hash.Thus my $j = <<EOF; {"monday":["blue", "black"], "tuesday":["grey", "heart attack"], "friday":"Gotta get down on Friday"} EOF my $p = parse_json ($j); has the same result as a Perl declaration of the form my $p = { monday => ['blue', 'black'], tuesday => ['grey', 'heart attack'], friday => 'Gotta get down on Friday', }; Key collisions A key collision is something like the following. use JSON::Parse qw/parse_json parse_json_safe/; my $j = '{"a":1, "a":2}'; my $p = parse_json ($j); print "Ambiguous key 'a' is ", $p->{a}, "\n"; my $q = parse_json_safe ($j); produces output JSON::Parse::parse_json_safe: Name is not unique: "a" parsing object starting from byte 1 at /usr/home/ben/projects/json-parse/examples/key-collision.pl line 8. Ambiguous key 'a' is 2 (This example is included as key-collision.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/key-collision.pl> in the distribution.) Here the key "a" could be either 1 or 2. As seen in the example, "parse_json" overwrites the first value with the second value. "parse_json_safe" halts and prints a warning. If you use "new" you can switch key collision on and off with the "detect_collisions" method. The rationale for "parse_json" not to give warnings is that Perl doesn't give information about collisions when storing into hash values, and checking for collisions for every key will degrade performance for the sake of an unlikely occurrence. The JSON specification says "The names within an object SHOULD be unique." (see "RFC 8259", page 5), although it's not a requirement. For performance, "valid_json" and "assert_valid_json" do not store hash keys, thus they cannot detect this variety of problem. Literalsfalse"parse_json" maps the JSON false literal to a readonly scalar which evaluates to the empty string, or to zero in a numeric context. (This behaviour changed from version 0.36 to 0.37. In versions up to 0.36, the false literal was mapped to a readonly scalar which evaluated to 0 only.) "parse_json_safe" maps the JSON literal to a similar scalar without the readonly constraints. If you use a parser created with "new", you can choose either of these behaviours with "copy_literals", or you can tell JSON::Parse to put your own value in place of falses using the "set_false" method. null "parse_json" maps the JSON null literal to a readonly scalar $JSON::Parse::null which evaluates to "undef". "parse_json_safe" maps the JSON literal to the undefined value. If you use a parser created with "new", you can choose either of these behaviours with "copy_literals", or you can tell JSON::Parse to put your own value in place of nulls using the "set_null" method. true "parse_json" maps the JSON true literal to a readonly scalar which evaluates to 1. "parse_json_safe" maps the JSON literal to the value 1. If you use a parser created with "new", you can choose either of these behaviours with "copy_literals", or you can tell JSON::Parse to put your own value in place of trues using the "set_true" method. Round trips and compatibility The Perl versions of literals produced by "parse_json" will be converted back to JSON literals if you use "create_json" in JSON::Create. However, JSON::Parse's literals are incompatible with the other CPAN JSON modules. For compatibility with other CPAN modules, create a JSON::Parse object with "new", and set JSON::Parse's literals with "set_true", "set_false", and "set_null". A round trip with JSON::Tiny This example demonstrates round-trip compatibility using JSON::Tiny, version 0.58: use utf8; use JSON::Tiny '0.58', qw(decode_json encode_json); use JSON::Parse; use JSON::Create; my $cream = '{"clapton":true,"hendrix":false}'; my $jp = JSON::Parse->new (); my $jc = JSON::Create->new (sort => 1); print "First do a round-trip of our modules:\n\n"; print $jc->create ($jp->parse ($cream)), "\n\n"; print "Now do a round-trip of JSON::Tiny:\n\n"; print encode_json (decode_json ($cream)), "\n\n"; print "🥴 First, incompatible mode:\n\n"; print 'tiny(parse): ', encode_json ($jp->parse ($cream)), "\n"; print 'create(tiny): ', $jc->create (decode_json ($cream)), "\n\n"; # Set our parser to produce these things as literals: $jp->set_true (JSON::Tiny::true); $jp->set_false (JSON::Tiny::false); print "🔄 Compatibility with JSON::Parse:\n\n"; print 'tiny(parse):', encode_json ($jp->parse ($cream)), "\n\n"; $jc->bool ('JSON::Tiny::_Bool'); print "🔄 Compatibility with JSON::Create:\n\n"; print 'create(tiny):', $jc->create (decode_json ($cream)), "\n\n"; print "🔄 JSON::Parse and JSON::Create are still compatible too:\n\n"; print $jc->create ($jp->parse ($cream)), "\n"; produces output First do a round-trip of our modules: {"clapton":true,"hendrix":false} Now do a round-trip of JSON::Tiny: {"clapton":true,"hendrix":false} 🥴 First, incompatible mode: tiny(parse): {"clapton":1,"hendrix":""} create(tiny): {"clapton":1,"hendrix":0} 🔄 Compatibility with JSON::Parse: tiny(parse):{"clapton":true,"hendrix":false} 🔄 Compatibility with JSON::Create: create(tiny):{"clapton":true,"hendrix":false} 🔄 JSON::Parse and JSON::Create are still compatible too: {"clapton":true,"hendrix":false} (This example is included as json-tiny-round-trip-demo.pl <https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.61/examples/json-tiny-round-trip-demo.pl> in the distribution.) Most of the other CPAN modules use similar methods to JSON::Tiny, so the above example can easily be adapted. See also "Interoperability" in JSON::Create for various examples. Modifying the values "parse_json" maps all the literals to read-only values. Because of this, attempting to modifying the boolean values in the hash reference returned by "parse_json" will cause "Modification of a read-only value attempted" errors: my $in = '{"hocus":true,"pocus":false,"focus":null}'; my $p = json_parse ($in); $p->{hocus} = 99; # "Modification of a read-only value attempted" error occurs Since the hash values are read-only scalars, "$p->{hocus} = 99" is like this: undef = 99; If you need to modify the returned hash reference, then delete the value first: my $in = '{"hocus":true,"pocus":false,"focus":null}'; my $p = json_parse ($in); delete $p->{pocus}; $p->{pocus} = 99; # OK Similarly with array references, delete the value before altering: my $in = '[true,false,null]'; my $q = json_parse ($in); delete $q->[1]; $q->[1] = 'magic'; Note that the return values from parsing bare literals are not read-only scalars, so my $true = JSON::Parse::json_parse ('true'); $true = 99; produces no error. This is because Perl copies the scalar. RESTRICTIONSThis module imposes the following restrictions on its input.
DIAGNOSTICS"valid_json" does not produce error messages. "parse_json" and "assert_valid_json" die on encountering invalid input. "parse_json_safe" uses "carp" in Carp to pass error messages as warnings.Error messages have the line number, and the byte number where appropriate, of the input which caused the problem. The line number is formed simply by counting the number of "\n" (linefeed, ASCII 0x0A) characters in the whitespace part of the JSON. In "parse_json" and "assert_valid_json", parsing errors are fatal, so to continue after an error occurs, put the parsing into an "eval" block: my $p; eval { $p = parse_json ($j); }; if ($@) { # handle error } The following error messages are produced:
PERFORMANCEOn the author's computer, the module's speed of parsing is approximately the same as JSON::XS, with small variations depending on the type of input. For validation, "valid_json" is faster than any other module known to the author, and up to ten times faster than JSON::XS.Some special types of input, such as floating point numbers containing an exponential part, like "1e09", seem to be about two or three times faster to parse with this module than with JSON::XS. In JSON::Parse, parsing of exponentials is done by the system's "strtod" function, but JSON::XS contains its own parser for exponentials, so these results may be system-dependent. At the moment the main place JSON::XS wins over JSON::Parse is in strings containing escape characters, where JSON::XS is about 10% faster on the module author's computer and compiler. As of version 0.33, despite some progress in improving JSON::Parse, I haven't been able to fully work out the reason behind the better speed. There is some benchmarking code in the github repository under the directory "benchmarks" for those wishing to test these claims. The script benchmarks/bench <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/benchmarks/bench> is an adaptation of the similar script in the JSON::XS distribution. The script benchmarks/pub-bench.pl <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/benchmarks/pub-bench.pl> runs the benchmarks and prints them out as POD. The following benchmark tests used version 0.58_01 of JSON::Parse, version 4.03 of "JSON::XS", and version 4.25 of "Cpanel::JSON::XS" on Perl version v5.32.0 compiled with Clang version FreeBSD clang version 10.0.1 on FreeBSD 12.2. The files in the "benchmarks" directory of JSON::Parse. short.json and long.json are the benchmarks used by "JSON::XS".
SEE ALSO
Other CPAN modules for parsing and producing JSONThe ⭐ represents the number of votes this module has received on metacpan, on a logarithmic scale. Modules which we recommend are marked with 👍. Deprecated modules and modules which are definitely buggy (bug reports/pull requests ignored) and abandoned (no releases for several years) are marked with 👎 and/or 🐛. Modules we can't work out are marked with 😕.
If you use this module from the command-line, the last
value of your one-liner (-e) code will be serialized as JSON data.
Don't make me think and give me what I want! This module
automatically figures out whether you want to encode a Perl data structure to
JSON or decode a JSON string to a Perl data structure.
SCRIPTA script "validjson" is supplied with the module. This runs "assert_valid_json" on its inputs, so run it like this.validjson *.json The default behaviour is to just do nothing if the input is valid. For invalid input it prints what the problem is: validjson ids.go ids.go: JSON error at line 1, byte 1/7588: Unexpected character '/' parsing initial state: expecting whitespace: '\n', '\r', '\t', ' ' or start of string: '"' or digit: '0-9' or minus: '-' or start of an array or object: '{', '[' or start of literal: 't', 'f', 'n'. If you need confirmation, use its --verbose option: validjson -v *.json atoms.json is valid JSON. ids.json is valid JSON. kanjidic.json is valid JSON. linedecomps.json is valid JSON. radkfile-radicals.json is valid JSON. DEPENDENCIES
EXPORTSThe module exports nothing by default. Functions "parse_json", "parse_json_safe", "read_json", "valid_json" and "assert_valid_json", as well as the old function names "validate_json", "json_file_to_perl", and "json_to_perl", can be exported on request.All of the functions can be exported using the tag ':all': use JSON::Parse ':all'; TESTINGInternal testing codeThe module incorporates extensive testing related to the production of error messages and validation of input. Some of the testing code is supplied with the module in the /t/ subdirectory of the distribution.More extensive testing code is in the git repository. This is not supplied in the CPAN distribution. A script, randomjson.pl <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/randomjson.pl>, generates a set number of bytes of random JSON and checks that the module's bytewise validation of input is correct. It does this by taking a valid fragment, then adding each possible byte from 0 to 255 to see whether the module correctly identifies it as valid or invalid at that point, then randomly picking one of the valid bytes and adding it to the fragment and continuing the process until a complete valid JSON input is formed. The module has undergone about a billion repetitions of this test. This setup relies on a C file, json-random-test.c <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/json-random-test.c>, which isn't in the CPAN distribution, and it also requires Json3.xs <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/Json3.xs> to be edited to make the macro "TESTRANDOM" true (uncomment line 7 of the file). The testing code uses C setjmp/longjmp, so it's not guaranteed to work on all operating systems and is commented out for CPAN releases. A pure C version called random-test.c <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/random-test.c> also exists. This applies exactly the same tests, and requires no Perl at all. If you're interested in testing your own JSON parser, the outputs generated by randomjson.pl <https://github.com/benkasminbullock/JSON-Parse/033269fa8972fdce8626aa65cd11a5394ab50492/randomjson.pl> are quite a good place to start. The default is to produce UTF-8 output, which looks pretty horrible since it tends to produce long strings of UTF-8 garbage. (This is because it chooses randomly from 256 bytes and the end-of-string marker """ has only a 1/256 chance of being chosen, so the strings tend to get long and messy). You can mess with the internals of JSON::Parse by setting MAXBYTE in json-common.c to 0x80, recompiling (you can ignore the compiler warnings), and running randomjson.pl again to get just ASCII random JSON things. This breaks the UTF-8 functionality of JSON::Parse, so please don't install that version. JSON Parsing Test SuiteJSON::Parse version 0.58 passes most of the JSON Parsing Test Suite, with the exception that JSON::Parse rejects various erroneous UTF-8 inputs, for example JSON::Parse will throw an error for non-character code points like Unicode U+FFFF and U+10FFFF. This parser only accepts valid UTF-8 as input. See "UTF-8 only".In our opinion it would be a disservice to users of this module to allow bytes containing useless fragments such as incomplete parts of surrogate pairs, or invalid characters, just because the JSON specification doesn't actually explicitly demand rejecting these kinds of garbage inputs. Please see the function "daft_test" in the file xt/JPXT.pm for exactly which of these elements of the test suite we do not comply with. We note that this comment from Douglas Crockford, the inventor of JSON, JSON parser <https://github.com/douglascrockford/JSON-c/blob/master/utf8_decode.c#L38-L43>, dated 2005, agrees with our opinion on this point. JSON::Parse version 0.58 also introduced "get_max_depth" and "set_max_depth" to prevent the stack overflow errors caused by some very deeply nested inputs such as those of the JSON Parsing Test Suite. ACKNOWLEDGEMENTSToby Inkster (TOBYINK) suggested some of the new function names which replaced the "OLD INTERFACE" names. Nicolas Immelman and Shlomi Fish (SHLOMIF) reported memory leaks which were fixed in 0.32 and 0.40. Github user kolmogorov42 reported a bug which led to 0.42. Github user SteveGlassman found an error in string copying for long strings, fixed in 0.57. Lars Dɪᴇᴄᴋᴏᴡ (DAXIM) pointed out problems with the JSON Parsing Test Suite which led to the addition of stack protection and "set_max_depth" and "get_max_depth" in 0.58.AUTHORBen Bullock, <bkb@cpan.org>COPYRIGHT & LICENCEThis package and associated files are copyright (C) 2013-2021 Ben Bullock.You can use, copy, modify and redistribute this package and associated files under the Perl Artistic Licence or the GNU General Public Licence.
Visit the GSP FreeBSD Man Page Interface. |