JSON-Path-0.431/0000775000175000017500000000000014004641374011703 5ustar tooktookJSON-Path-0.431/META.yml0000644000175000017500000000320314004641374013150 0ustar tooktook--- abstract: 'search nested hashref/arrayref structures using JSONPath' author: - 'Kit Peters ' build_requires: ExtUtils::MakeMaker: '0' File::Spec: '0' JSON: '0' JSON::Parse: '0' Test2::V0: '0' Test::Deep: '0' Test::More: '0' Test::Most: '0' Tie::IxHash: '0' perl: '5.016' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.017, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: JSON-Path no_index: directory: - eg - examples - inc - share - t - xt provides: JSON::Path: file: lib/JSON/Path.pm version: '0.431' JSON::Path::Constants: file: lib/JSON/Path/Constants.pm version: '0.431' JSON::Path::Evaluator: file: lib/JSON/Path/Evaluator.pm version: '0.431' JSON::Path::Tokenizer: file: lib/JSON/Path/Tokenizer.pm version: '0.431' requires: Carp: '0' Carp::Assert: '0' Exporter: '0' Exporter::Easy: '0' Exporter::Tiny: '0' JSON::MaybeXS: '0' LV: '0' List::Util: '1.48' Readonly: '0' Safe: '0' Scalar::Util: '0' Storable: '0' Sys::Hostname: '0' Try::Tiny: '0' base: '0' overload: '0' perl: '5.016' strict: '0' warnings: '0' resources: bugtracker: https://github.com/popefelix/p5-json-path/issues homepage: https://github.com/popefelix/p5-json-path repository: https://github.com/popefelix/p5-json-path.git version: '0.431' x_generated_by_perl: v5.26.1 x_serialization_backend: 'YAML::Tiny version 1.73' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' JSON-Path-0.431/MANIFEST0000644000175000017500000000152714004641374013037 0ustar tooktook# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.017. Changes LICENSE MANIFEST META.json META.yml Makefile.PL README dist.ini examples/eg1.pl lib/JSON/Path.pm lib/JSON/Path/Constants.pm lib/JSON/Path/Evaluator.pm lib/JSON/Path/Tokenizer.pm meta/changes.pret meta/doap.pret meta/makefile.pret t/00-report-prereqs.dd t/00-report-prereqs.t t/01basic.t t/02zeroth.t t/03shortcuts.t t/04map.t t/05set.t t/06lvalue.t t/07utf8.t t/08context.t t/dots_in_path.t t/evaluator/path-construction-fail.t t/evaluator/paths.t t/evaluator/refs.t t/evaluator/tokenize.t t/evaluator/want_path.t t/hashref_not_modified.t t/multiple-recursion.t t/path-construction-failure.t weaver.ini xt/01pod.t xt/02pod_coverage.t xt/03meta_uptodate.config xt/03meta_uptodate.t xt/04eol.t xt/05tabs.t xt/06versions.t xt/author/00-compile.t xt/author/pod-syntax.t JSON-Path-0.431/meta/0000775000175000017500000000000014004641374012631 5ustar tooktookJSON-Path-0.431/meta/doap.pret0000644000175000017500000000162114004641374014446 0ustar tooktook# This file contains general metadata about the project. @prefix : . `JSON-Path` :programming-language "Perl" ; :shortdesc "search nested hashref/arrayref structures using JSONPath"; :homepage ; :download-page ; :bug-database ; :repository [ a :GitRepository; :browse ]; :created 2010-07-28; :license ; :maintainer cpan:TOBYINK; :developer cpan:TOBYINK. dc:title "the same terms as the perl 5 programming language system itself". cpan:TOBYINK foaf:name "Toby Inkster"; foaf:mbox . JSON-Path-0.431/meta/changes.pret0000644000175000017500000000626314004641374015142 0ustar tooktook# This file acts as the project's changelog. @prefix : . @prefix my: . my:v_0-080_00 a :Version ; dc:issued "2010-07-28"^^xsd:date ; :revision "0.080_00"^^xsd:string ; :file-release ; rdfs:label "Ported from PHP."@en . my:v_0-080_01 a :Version ; dc:issued "2010-07-29"^^xsd:date ; :revision "0.080_01"^^xsd:string ; :file-release ; dcs:changeset [ dcs:versus my:v_0-080_00 ; dcs:item [ rdfs:label "Fix license metadata in distribution."@en ; a dcs:Bugfix ] ] . my:v_0-100 a :Version ; dc:issued "2010-08-25"^^xsd:date ; :revision "0.100"^^xsd:string ; :file-release ; dcs:changeset [ dcs:versus my:v_0-080_01 ; dcs:item [ rdfs:label "Support for JSON::JOM."@en ; a dcs:Update ] ; dcs:item [ rdfs:label "Minor documentation improvements."@en ] ; ] . my:v_0-101 a :Version ; dc:issued "2011-09-29"^^xsd:date ; :revision "0.101"^^xsd:string ; :file-release ; dcs:changeset [ dcs:versus my:v_0-100 ; dcs:item [ rdfs:label "Fix retrieval of zeroth array element."@en ; a dcs:Bugfix ] ; dcs:item [ rdfs:label "Add more test cases."@en ; a dcs:Packaging ] ; ] . my:project :release my:v_0-080_00, my:v_0-080_01, my:v_0-100, my:v_0-101. # Pretdsl below here... `JSON-Path 0.200 cpan:TOBYINK` issued 2012-09-12; changeset [ item "Switch from Error.pm exceptions to Carp::croak."^^Update; item "Drop dependency on common::sense."^^Packaging; item "Modernize."^^Packaging; ]. `JSON-Path 0.201 cpan:TOBYINK` issued 2012-09-12; changeset [ item "Remove remaining `use Error` in test suite."^^Bugfix; ]. `JSON-Path 0.202 cpan:TOBYINK` issued 2012-10-12; changeset [ item "`value` method."^^Addition; item "`map` method."^^Addition; item "`get` and `set` methods."^^Addition; item "`jpath`, `jpath1` and `jpath_map` functions."^^Addition; ]. `JSON-Path 0.203 cpan:TOBYINK` issued 2012-10-12; changeset [ item "Minor corrections to pod."^^Documentation; ]. `JSON-Path 0.204 cpan:TOBYINK` issued 2013-02-14; changeset [ item "Corrections to lvalue documentation."^^Documentation; item "Add documentation to test suite."^^Documentation; item [ a dcs:Bugfix; label "Fix `set` method which was broken in some circumstances."; dcs:fixes RT#83249; dcs:thanks [ a foaf:Person; foaf:name "Mitsuhiro Nakamura" ]; ]; ]. `JSON-Path 0.205 cpan:TOBYINK` issued 2013-11-02; changeset [ item "Use Dist::Inkt."^^Packaging; item "Use LV instead of lvalue.pm."^^Change; item "Use Exporter::Tiny instead of Sub::Exporter."^^Change; item [ a dcs:Bugfix; label "Fix problem using JSON::Path with Devel::ptkdb."; dcs:fixes RT#89393; dcs:thanks [ a foaf:Person; foaf:name "Henri-Damien Laurent" ]; ]; ]. JSON-Path-0.431/meta/makefile.pret0000644000175000017500000000052614004641374015303 0ustar tooktook# This file provides instructions for packaging. `JSON-Path` deps:runtime-requirement [ deps:on "JSON::MaybeXS 1.003005"^^deps:CpanId ]; deps:runtime-requirement [ deps:on "Exporter::Tiny"^^deps:CpanId ]; deps:runtime-requirement [ deps:on "LV"^^deps:CpanId ]; deps:test-requirement [ deps:on "Test::More 0.61"^^deps:CpanId ]; . JSON-Path-0.431/LICENSE0000644000175000017500000004364714004641374012724 0ustar tooktookThis software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2021 by Kit Peters. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2021 by Kit Peters. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End JSON-Path-0.431/weaver.ini0000644000175000017500000000005614004641374013674 0ustar tooktook[@Default] [-Transformer] transformer = List JSON-Path-0.431/README0000644000175000017500000002113114004641374012557 0ustar tooktookNAME JSON::Path VERSION version 0.431 SYNOPSIS my $data = { "store" => { "book" => [ { "category" => "reference", "author" => "Nigel Rees", "title" => "Sayings of the Century", "price" => 8.95, }, { "category" => "fiction", "author" => "Evelyn Waugh", "title" => "Sword of Honour", "price" => 12.99, }, { "category" => "fiction", "author" => "Herman Melville", "title" => "Moby Dick", "isbn" => "0-553-21311-3", "price" => 8.99, }, { "category" => "fiction", "author" => "J. R. R. Tolkien", "title" => "The Lord of the Rings", "isbn" => "0-395-19395-8", "price" => 22.99, }, ], "bicycle" => [ { "color" => "red", "price" => 19.95, }, ], }, }; use JSON::Path 'jpath_map'; # All books in the store my $jpath = JSON::Path->new('$.store.book[*]'); my @books = $jpath->values($data); # The author of the last (by order) book my $jpath = JSON::Path->new('$..book[-1:].author'); my $tolkien = $jpath->value($data); # Convert all authors to uppercase jpath_map { uc $_ } $data, '$.store.book[*].author'; DESCRIPTION This module implements JSONPath, an XPath-like language for searching JSON-like structures. JSONPath is described at . Constructor "JSON::Path->new($string)" Given a JSONPath expression $string, returns a JSON::Path object. Methods "values($object)" Evaluates the JSONPath expression against an object. The object $object can be either a nested Perl hashref/arrayref structure, or a JSON string capable of being decoded by JSON::MaybeXS::decode_json. Returns a list of structures from within $object which match against the JSONPath expression. In scalar context, returns the number of matches. "value($object)" Like "values", but returns just the first value. This method is an lvalue sub, which means you can assign to it: my $person = { name => "Robert" }; my $path = JSON::Path->new('$.name'); $path->value($person) = "Bob"; TAKE NOTE! This will create keys in $object. E.G.: my $obj = { foo => 'bar' }; my $path = JSON::Path->new('$.baz'); $path->value($obj) = 'bak'; # $obj->{baz} is created and set to 'bak'; "paths($object)" As per "values" but instead of returning structures which match the expression, returns canonical JSONPaths that point towards those structures. "get($object)" In list context, identical to "values", but in scalar context returns the first result. "set($object, $value, $limit)" Alters $object, setting the paths to $value. If set, then $limit limits the number of changes made. TAKE NOTE! This will create keys in $object. E.G.: my $obj = { foo => 'bar' }; my $path = JSON::Path->new('$.baz'); $path->set($obj, 'bak'); # $obj->{baz} is created and set to 'bak' Returns the number of changes made. "map($object, $coderef)" Conceptually similar to Perl's "map" keyword. Executes the coderef (in scalar context!) for each match of the path within the object, and sets a new value from the coderef's return value. Within the coderef, $_ may be used to access the old value, and $. may be used to access the curent canonical JSONPath. "to_string" Returns the original JSONPath expression as a string. This method is usually not needed, as the JSON::Path should automatically stringify itself as appropriate. i.e. the following works: my $jpath = JSON::Path->new('$.store.book[*].author'); print "I'm looking for: " . $jpath . "\n"; Functions The following functions are available for export, but are not exported by default: "jpath($object, $path_string)" Shortcut for "JSON::Path->new($path_string)->values($object)". "jpath1($object, $path_string)" Shortcut for "JSON::Path->new($path_string)->value($object)". Like "value", it can be used as an lvalue. "jpath_map { CODE } $object, $path_string" Shortcut for "JSON::Path->new($path_string)->map($object, $code)". NAME JSON::Path - search nested hashref/arrayref structures using JSONPath PERL SPECIFICS JSONPath is intended as a cross-programming-language method of searching nested object structures. There are however, some things you need to think about when using JSONPath in Perl... JSONPath Embedded Perl Expressions JSONPath expressions may contain subexpressions that are evaluated using the native host language. e.g. $..book[?($_->{author} =~ /tolkien/i)] The stuff between "?(" and ")" is a Perl expression that must return a boolean, used to filter results. As arbitrary Perl may be used, this is clearly quite dangerous unless used in a controlled environment. Thus, it's disabled by default. To enable, set: $JSON::Path::Safe = 0; There are some differences between the JSONPath spec and this implementation. * JSONPath uses a variable '$' to refer to the root node. This is not a legal variable name in Perl, so '$root' is used instead. * JSONPath uses a variable '@' to refer to the current node. This is not a legal variable name in Perl, so '$_' is used instead. Blessed Objects Blessed objects are generally treated as atomic values; JSON::Path will not follow paths inside them. The exception to this rule are blessed objects where: Scalar::Util::blessed($object) && $object->can('typeof') && $object->typeof =~ /^(ARRAY|HASH)$/ which are treated as an unblessed arrayref or hashref appropriately. BUGS Please report any bugs to . SEE ALSO Specification: . Implementations in PHP, Javascript and C#: . Related modules: JSON, JSON::JOM, JSON::T, JSON::GRDDL, JSON::Hyper, JSON::Schema. Similar functionality: Data::Path, Data::DPath, Data::SPath, Hash::Path, Path::Resolver::Resolver::Hash, Data::Nested, Data::Hierarchy... yes, the idea's not especially new. What's different is that JSON::Path uses a vaguely standardised syntax with implementations in at least three other programming languages. AUTHOR Toby Inkster . MAINTAINER Kit Peters CONTRIBUTORS Szymon NieznaƄski Kit Peters Heiko Jansen . Mitsuhiro Nakamura COPYRIGHT AND LICENCE Copyright 2007 Stefan Goessner. Copyright 2010-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. a.k.a. "The MIT Licence" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. AUTHOR Kit Peters COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. JSON-Path-0.431/examples/0000775000175000017500000000000014004641374013521 5ustar tooktookJSON-Path-0.431/examples/eg1.pl0000644000175000017500000000236514004641374014536 0ustar tooktookuse 5.010; use JSON::MaybeXS; use Scalar::Util qw[blessed]; use lib "../lib"; use JSON::Path; my $json = JSON::MaybeXS->new( pretty => 1 ); my $object = $json->decode(<<'JSON'); { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } JSON $JSON::Path::Safe = 0; foreach ('$.store.book[0].title', '$.store.book[*].author', '$..author', '$..book[-1:]', '$..book[?($_->{author} =~ /tolkien/i)]') { my $jpath = JSON::Path->new($_); say $jpath; say $json->encode([$jpath->values($object)]); say $json->encode([$jpath->paths($object)]); say [$jpath->values($object)]->[0]->nodePath if blessed([$jpath->values($object)]->[0]); say '-' x 40; } JSON-Path-0.431/dist.ini0000644000175000017500000000106114004641374013343 0ustar tooktookname = JSON-Path author = Kit Peters license = Perl_5 copyright_holder = Kit Peters copyright_year = 2021 ; authordep Pod::Elemental::Transformer::List version = 0.431 [AutoPrereqs] [Prereqs] List::Util = 1.48 [@Starter] revision = 5 [GithubMeta] issues = 1 user = popefelix ;[@Git] [PodWeaver] [PkgVersion] [CheckChangeLog] [ ReadmeAnyFromPod / MarkdownInRoot ] filename = README.md [NextRelease] [MetaProvides::Package] ;[Git::Check] ;allow_dirty = dist.ini ;allow_dirty = META.json ;allow_dirty = README.md ;build_warnings = 1 JSON-Path-0.431/META.json0000644000175000017500000000641214004641374013325 0ustar tooktook{ "abstract" : "search nested hashref/arrayref structures using JSONPath", "author" : [ "Kit Peters " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.017, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "JSON-Path", "no_index" : { "directory" : [ "eg", "examples", "inc", "share", "t", "xt" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "File::Spec" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::EOL" : "0", "Test::HasVersion" : "0", "Test::More" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "0", "Test::RDF::DOAP::Version" : "0", "Test::Tabs" : "0", "XT::Util" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "Carp::Assert" : "0", "Exporter" : "0", "Exporter::Easy" : "0", "Exporter::Tiny" : "0", "JSON::MaybeXS" : "0", "LV" : "0", "List::Util" : "1.48", "Readonly" : "0", "Safe" : "0", "Scalar::Util" : "0", "Storable" : "0", "Sys::Hostname" : "0", "Try::Tiny" : "0", "base" : "0", "overload" : "0", "perl" : "5.016", "strict" : "0", "warnings" : "0" } }, "test" : { "recommends" : { "CPAN::Meta" : "2.120900" }, "requires" : { "ExtUtils::MakeMaker" : "0", "File::Spec" : "0", "JSON" : "0", "JSON::Parse" : "0", "Test2::V0" : "0", "Test::Deep" : "0", "Test::More" : "0", "Test::Most" : "0", "Tie::IxHash" : "0", "perl" : "5.016" } } }, "provides" : { "JSON::Path" : { "file" : "lib/JSON/Path.pm", "version" : "0.431" }, "JSON::Path::Constants" : { "file" : "lib/JSON/Path/Constants.pm", "version" : "0.431" }, "JSON::Path::Evaluator" : { "file" : "lib/JSON/Path/Evaluator.pm", "version" : "0.431" }, "JSON::Path::Tokenizer" : { "file" : "lib/JSON/Path/Tokenizer.pm", "version" : "0.431" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/popefelix/p5-json-path/issues" }, "homepage" : "https://github.com/popefelix/p5-json-path", "repository" : { "type" : "git", "url" : "https://github.com/popefelix/p5-json-path.git", "web" : "https://github.com/popefelix/p5-json-path" } }, "version" : "0.431", "x_generated_by_perl" : "v5.26.1", "x_serialization_backend" : "Cpanel::JSON::XS version 4.25", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } JSON-Path-0.431/xt/0000775000175000017500000000000014004641374012336 5ustar tooktookJSON-Path-0.431/xt/author/0000775000175000017500000000000014004641374013640 5ustar tooktookJSON-Path-0.431/xt/author/00-compile.t0000644000175000017500000000267314004641374015700 0ustar tooktookuse 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.058 use Test::More; plan tests => 5; my @module_files = ( 'JSON/Path.pm', 'JSON/Path/Constants.pm', 'JSON/Path/Evaluator.pm', 'JSON/Path/Tokenizer.pm' ); # no fake home requested my @switches = ( -d 'blib' ? '-Mblib' : '-Ilib', ); use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; diag('Running: ', join(', ', map { my $str = $_; $str =~ s/'/\\'/g; q{'} . $str . q{'} } $^X, @switches, '-e', "require q[$lib]")) if $ENV{PERL_COMPILE_TEST_DEBUG}; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, @switches, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); shift @_warnings if @_warnings and $_warnings[0] =~ /^Using .*\bblib/ and not eval { +require blib; blib->VERSION('1.01') }; if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') or diag 'got warnings: ', ( Test::More->can('explain') ? Test::More::explain(\@warnings) : join("\n", '', @warnings) ); JSON-Path-0.431/xt/author/pod-syntax.t0000644000175000017500000000025214004641374016130 0ustar tooktook#!perl # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use strict; use warnings; use Test::More; use Test::Pod 1.41; all_pod_files_ok(); JSON-Path-0.431/xt/06versions.t0000644000175000017500000000047014004641374014540 0ustar tooktookuse XT::Util; use Test::More; use Test::HasVersion; plan skip_all => __CONFIG__->{skip_all} if __CONFIG__->{skip_all}; if ( __CONFIG__->{modules} ) { my @modules = @{ __CONFIG__->{modules} }; pm_version_ok($_, "$_ is covered") for @modules; done_testing(scalar @modules); } else { all_pm_version_ok(); } JSON-Path-0.431/xt/03meta_uptodate.t0000644000175000017500000000021414004641374015514 0ustar tooktookuse XT::Util; use Test::More tests => 1; use Test::RDF::DOAP::Version; doap_version_ok(__CONFIG__->{package}, __CONFIG__->{version_from}); JSON-Path-0.431/xt/05tabs.t0000644000175000017500000000004514004641374013616 0ustar tooktookuse Test::Tabs; all_perl_files_ok(); JSON-Path-0.431/xt/01pod.t0000644000175000017500000000020214004641374013436 0ustar tooktookuse Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); JSON-Path-0.431/xt/03meta_uptodate.config0000644000175000017500000000003014004641374016512 0ustar tooktook{"package":"JSON-Path"} JSON-Path-0.431/xt/02pod_coverage.t0000644000175000017500000000047714004641374015330 0ustar tooktookuse XT::Util; use Test::More; use Test::Pod::Coverage; plan skip_all => __CONFIG__->{skip_all} if __CONFIG__->{skip_all}; if ( __CONFIG__->{modules} ) { my @modules = @{ __CONFIG__->{modules} }; pod_coverage_ok($_, "$_ is covered") for @modules; done_testing(scalar @modules); } else { all_pod_coverage_ok(); } JSON-Path-0.431/xt/04eol.t0000644000175000017500000000004414004641374013442 0ustar tooktookuse Test::EOL; all_perl_files_ok(); JSON-Path-0.431/Makefile.PL0000644000175000017500000000413414004641374013655 0ustar tooktook# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.017. use strict; use warnings; use 5.016; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "search nested hashref/arrayref structures using JSONPath", "AUTHOR" => "Kit Peters ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "JSON-Path", "LICENSE" => "perl", "MIN_PERL_VERSION" => "5.016", "NAME" => "JSON::Path", "PREREQ_PM" => { "Carp" => 0, "Carp::Assert" => 0, "Exporter" => 0, "Exporter::Easy" => 0, "Exporter::Tiny" => 0, "JSON::MaybeXS" => 0, "LV" => 0, "List::Util" => "1.48", "Readonly" => 0, "Safe" => 0, "Scalar::Util" => 0, "Storable" => 0, "Sys::Hostname" => 0, "Try::Tiny" => 0, "base" => 0, "overload" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "JSON" => 0, "JSON::Parse" => 0, "Test2::V0" => 0, "Test::Deep" => 0, "Test::More" => 0, "Test::Most" => 0, "Tie::IxHash" => 0 }, "VERSION" => "0.431", "test" => { "TESTS" => "t/*.t t/evaluator/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "Carp::Assert" => 0, "Exporter" => 0, "Exporter::Easy" => 0, "Exporter::Tiny" => 0, "ExtUtils::MakeMaker" => 0, "File::Spec" => 0, "JSON" => 0, "JSON::MaybeXS" => 0, "JSON::Parse" => 0, "LV" => 0, "List::Util" => "1.48", "Readonly" => 0, "Safe" => 0, "Scalar::Util" => 0, "Storable" => 0, "Sys::Hostname" => 0, "Test2::V0" => 0, "Test::Deep" => 0, "Test::More" => 0, "Test::Most" => 0, "Tie::IxHash" => 0, "Try::Tiny" => 0, "base" => 0, "overload" => 0, "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); JSON-Path-0.431/Changes0000644000175000017500000000312414004641374013174 0ustar tooktook0.431 2021-01-28 17:04:25-06:00 America/Chicago [ Other ] - Fix the local/ directory being included in the distro 0.430 2021-01-27 23:34:50-06:00 America/Chicago [ Bug Fixes ] - multiple recursion (e.g. $..foo..bar) works properly. Fixes RT #122529 Thomas Helsel ++ - Non-array-like and non-hash-like refs work properly for paths and map. Fixes RT #123381 Patrick Cronin++ [ Other ] - Warnings at the calling line when attempting to set on a non-object via set() or value() as an lvalue 0.401 2017-07-20 09:24:14-05:00 America/Chicago [ Other ] Changes to build files only 0.400 2017-07-17 17:44:44-05:00 America/Chicago [ Other ] Tokenizer has been rewritten and is now cleaner and 20% cooler. [ Bug Fixes ] - get() no longer creates keys in the object Fixes RT #122493 Thomas Helsel++ - Fix for path construction failure when expression contains a filter Fixes RT 122190 James Bowery++ 0.310 2017-07-11 13:36:54-05:00 America/Chicago [ Bug Fixes ] - Fixes RT #122427 Slaven Rezic++ 0.301 2017-07-10 16:37:15-05:00 America/Chicago [ Bug Fixes ] - Fix missing version information in main module 0.300 2017-07-10 11:13:48-05:00 America/Chicago [ Bug Fixes ] - Add support for escaping reserved characters Fixes RT #92237 Max Laager++ [ Other ] - Setting values on non-existent keys will create the key with the value - Forked from Toby Inkster's JSON::Path 0.205 JSON-Path-0.431/lib/0000775000175000017500000000000014004641374012451 5ustar tooktookJSON-Path-0.431/lib/JSON/0000775000175000017500000000000014004641374013222 5ustar tooktookJSON-Path-0.431/lib/JSON/Path.pm0000644000175000017500000002666214004641374014466 0ustar tooktookuse 5.008; use strict; use warnings; package JSON::Path; $JSON::Path::VERSION = '0.431'; # VERSION use Exporter::Tiny (); our @ISA = qw/ Exporter::Tiny /; our $AUTHORITY = 'cpan:POPEFELIX'; our $Safe = 1; use Carp; use JSON::MaybeXS qw/decode_json/; use JSON::Path::Evaluator; use Scalar::Util qw[blessed]; use LV (); our @EXPORT_OK = qw/ jpath jpath1 jpath_map /; use overload '""' => \&to_string; sub jpath { my ( $object, $expression ) = @_; my @return = __PACKAGE__->new($expression)->values($object); } sub jpath1 : lvalue { my ( $object, $expression ) = @_; __PACKAGE__->new($expression)->value($object); } sub jpath_map (&$$) { my ( $coderef, $object, $expression ) = @_; return __PACKAGE__->new($expression)->map( $object, $coderef ); } sub new { my ( $class, $expression ) = @_; return $expression if blessed($expression) && $expression->isa(__PACKAGE__); return bless \$expression, $class; } sub to_string { my ($self) = @_; return $$self; } sub paths { my ( $self, $object ) = @_; my @paths = JSON::Path::Evaluator::evaluate_jsonpath( $object, "$self", want_path => 1); return @paths; } sub get { my ( $self, $object ) = @_; my @values = $self->values($object); return wantarray ? @values : $values[0]; } sub set { my ( $self, $object, $value, $limit ) = @_; if ( !ref $object ) { # warn if not called internally. If called internally (i.e. from value()) we will already have warned. my @c = caller(0); if ( $c[1] !~ /JSON\/Path\.pm$/ ) { carp qq{Useless attempt to set a value on a non-reference}; } } my $count = 0; my @refs = JSON::Path::Evaluator::evaluate_jsonpath( $object, "$self", want_ref => 1 ); for my $ref (@refs) { ${$ref} = $value; ++$count; last if $limit && ( $count >= $limit ); } return $count; } sub value : lvalue { my ( $self, $object ) = @_; LV::lvalue( get => sub { my ($value) = $self->get($object); return $value; }, set => sub { my $value = shift; # do some caller() magic to warn at the right place if ( !ref $object ) { my @c = caller(2); my ( $filename, $line ) = @c[ 1, 2 ]; warn qq{Useless attempt to set a value on a non-reference at $filename line $line\n}; } $self->set( $object, $value, 1 ); }, ); } sub values { my ( $self, $object ) = @_; croak q{non-safe evaluation, died} if "$self" =~ /\?\(/ && $JSON::Path::Safe; return JSON::Path::Evaluator::evaluate_jsonpath( $object, "$self", script_engine => 'perl' ); } sub map { my ( $self, $object, $coderef ) = @_; my $count; foreach my $path ( $self->paths( $object ) ) { my ($ref) = JSON::Path::Evaluator::evaluate_jsonpath( $object, $path, want_ref => 1 ); ++$count; my $value = do { no warnings 'numeric'; local $_ = ${$ref}; local $. = $path; scalar $coderef->(); }; ${$ref} = $value; } return $count; } 1; __END__ =pod =encoding UTF-8 =head1 NAME JSON::Path =head1 VERSION version 0.431 =head1 SYNOPSIS my $data = { "store" => { "book" => [ { "category" => "reference", "author" => "Nigel Rees", "title" => "Sayings of the Century", "price" => 8.95, }, { "category" => "fiction", "author" => "Evelyn Waugh", "title" => "Sword of Honour", "price" => 12.99, }, { "category" => "fiction", "author" => "Herman Melville", "title" => "Moby Dick", "isbn" => "0-553-21311-3", "price" => 8.99, }, { "category" => "fiction", "author" => "J. R. R. Tolkien", "title" => "The Lord of the Rings", "isbn" => "0-395-19395-8", "price" => 22.99, }, ], "bicycle" => [ { "color" => "red", "price" => 19.95, }, ], }, }; use JSON::Path 'jpath_map'; # All books in the store my $jpath = JSON::Path->new('$.store.book[*]'); my @books = $jpath->values($data); # The author of the last (by order) book my $jpath = JSON::Path->new('$..book[-1:].author'); my $tolkien = $jpath->value($data); # Convert all authors to uppercase jpath_map { uc $_ } $data, '$.store.book[*].author'; =head1 DESCRIPTION This module implements JSONPath, an XPath-like language for searching JSON-like structures. JSONPath is described at L. =head2 Constructor =over 4 =item C<< JSON::Path->new($string) >> Given a JSONPath expression $string, returns a JSON::Path object. =back =head2 Methods =over 4 =item C<< values($object) >> Evaluates the JSONPath expression against an object. The object $object can be either a nested Perl hashref/arrayref structure, or a JSON string capable of being decoded by JSON::MaybeXS::decode_json. Returns a list of structures from within $object which match against the JSONPath expression. In scalar context, returns the number of matches. =item C<< value($object) >> Like C, but returns just the first value. This method is an lvalue sub, which means you can assign to it: my $person = { name => "Robert" }; my $path = JSON::Path->new('$.name'); $path->value($person) = "Bob"; TAKE NOTE! This will create keys in $object. E.G.: my $obj = { foo => 'bar' }; my $path = JSON::Path->new('$.baz'); $path->value($obj) = 'bak'; # $obj->{baz} is created and set to 'bak'; =item C<< paths($object) >> As per C but instead of returning structures which match the expression, returns canonical JSONPaths that point towards those structures. =item C<< get($object) >> In list context, identical to C<< values >>, but in scalar context returns the first result. =item C<< set($object, $value, $limit) >> Alters C<< $object >>, setting the paths to C<< $value >>. If set, then C<< $limit >> limits the number of changes made. TAKE NOTE! This will create keys in $object. E.G.: my $obj = { foo => 'bar' }; my $path = JSON::Path->new('$.baz'); $path->set($obj, 'bak'); # $obj->{baz} is created and set to 'bak' Returns the number of changes made. =item C<< map($object, $coderef) >> Conceptually similar to Perl's C keyword. Executes the coderef (in scalar context!) for each match of the path within the object, and sets a new value from the coderef's return value. Within the coderef, C<< $_ >> may be used to access the old value, and C<< $. >> may be used to access the curent canonical JSONPath. =item C<< to_string >> Returns the original JSONPath expression as a string. This method is usually not needed, as the JSON::Path should automatically stringify itself as appropriate. i.e. the following works: my $jpath = JSON::Path->new('$.store.book[*].author'); print "I'm looking for: " . $jpath . "\n"; =back =head2 Functions The following functions are available for export, but are not exported by default: =over =item C<< jpath($object, $path_string) >> Shortcut for C<< JSON::Path->new($path_string)->values($object) >>. =item C<< jpath1($object, $path_string) >> Shortcut for C<< JSON::Path->new($path_string)->value($object) >>. Like C, it can be used as an lvalue. =item C<< jpath_map { CODE } $object, $path_string >> Shortcut for C<< JSON::Path->new($path_string)->map($object, $code) >>. =back =head1 NAME JSON::Path - search nested hashref/arrayref structures using JSONPath =head1 PERL SPECIFICS JSONPath is intended as a cross-programming-language method of searching nested object structures. There are however, some things you need to think about when using JSONPath in Perl... =head2 JSONPath Embedded Perl Expressions JSONPath expressions may contain subexpressions that are evaluated using the native host language. e.g. $..book[?($_->{author} =~ /tolkien/i)] The stuff between "?(" and ")" is a Perl expression that must return a boolean, used to filter results. As arbitrary Perl may be used, this is clearly quite dangerous unless used in a controlled environment. Thus, it's disabled by default. To enable, set: $JSON::Path::Safe = 0; There are some differences between the JSONPath spec and this implementation. =over 4 =item * JSONPath uses a variable '$' to refer to the root node. This is not a legal variable name in Perl, so '$root' is used instead. =item * JSONPath uses a variable '@' to refer to the current node. This is not a legal variable name in Perl, so '$_' is used instead. =back =head2 Blessed Objects Blessed objects are generally treated as atomic values; JSON::Path will not follow paths inside them. The exception to this rule are blessed objects where: Scalar::Util::blessed($object) && $object->can('typeof') && $object->typeof =~ /^(ARRAY|HASH)$/ which are treated as an unblessed arrayref or hashref appropriately. =head1 BUGS Please report any bugs to L. =head1 SEE ALSO Specification: L. Implementations in PHP, Javascript and C#: L. Related modules: L, L, L, L, L, L. Similar functionality: L, L, L, L, L, L, L... yes, the idea's not especially new. What's different is that JSON::Path uses a vaguely standardised syntax with implementations in at least three other programming languages. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 MAINTAINER Kit Peters Epopefelix@cpan.orgE =head1 CONTRIBUTORS Szymon NieznaƄski Es.nez@member.fsf.orgE Kit Peters Epopefelix@cpan.orgE Heiko Jansen Ehjansen@cpan.orgE. Mitsuhiro Nakamura Em.nacamura@gmail.comE =head1 COPYRIGHT AND LICENCE Copyright 2007 Stefan Goessner. Copyright 2010-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =head2 a.k.a. "The MIT Licence" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =head1 AUTHOR Kit Peters =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut JSON-Path-0.431/lib/JSON/Path/0000775000175000017500000000000014004641374014116 5ustar tooktookJSON-Path-0.431/lib/JSON/Path/Tokenizer.pm0000644000175000017500000000716014004641374016430 0ustar tooktookpackage JSON::Path::Tokenizer; $JSON::Path::Tokenizer::VERSION = '0.431'; use strict; use warnings; use 5.008; use Carp; use Readonly; use JSON::Path::Constants qw(:symbols :operators); use Exporter::Easy ( OK => ['tokenize'] ); Readonly my $ESCAPE_CHAR => qq{\\}; Readonly my %OPERATORS => ( $TOKEN_ROOT => 1, # $ $TOKEN_RECURSIVE => 1, # .. $TOKEN_CHILD => 1, # . $TOKEN_FILTER_OPEN => 1, # [?( $TOKEN_FILTER_SCRIPT_CLOSE => 1, # )] $TOKEN_SCRIPT_OPEN => 1, # [( $TOKEN_SUBSCRIPT_OPEN => 1, # [ $TOKEN_SUBSCRIPT_CLOSE => 1, # ] ); # ABSTRACT: Helper class for JSON::Path::Evaluator. Do not call directly. # Take an expression and break it up into tokens sub tokenize { my $expression = shift; my $chars = [ split //, $expression ]; my @tokens; while ( defined( my $token = _read_to_next_token($chars) ) ) { push @tokens, $token; if ( $token eq $TOKEN_SCRIPT_OPEN || $token eq $TOKEN_FILTER_OPEN ) { push @tokens, _read_to_filter_script_close($chars); } } return @tokens; } sub _read_to_filter_script_close { my $chars = shift; my $filter; while ( defined( my $char = shift @{$chars} ) ) { $filter .= $char; last unless @{$chars}; last if $chars->[0] eq $RIGHT_PARENTHESIS; } return $filter; } sub _read_to_next_token { my $chars = shift; my $in_quote; my $token; while ( defined( my $char = shift @{$chars} ) ) { if ( $char eq $APOSTROPHE || $char eq $QUOTATION_MARK ) { if ( $in_quote && $in_quote eq $char ) { $in_quote = ''; last; } $in_quote = $char; next; } if ( $char eq $ESCAPE_CHAR && !$in_quote ) { $token .= shift @{$chars}; next; } $token .= $char; next if $in_quote; # Break out of the loop if the current character is the last one in the stream. last unless @{$chars}; if ( $char eq $LEFT_SQUARE_BRACKET ) { # distinguish between '[', '[(', and '[?(' if ( $chars->[0] eq $LEFT_PARENTHESIS ) { next; } if ( $chars->[0] eq $QUESTION_MARK ) { # The below appends the '?'. The '(' will be appended in the next iteration of the loop $token .= shift @{$chars}; next; } } elsif ( $char eq $RIGHT_PARENTHESIS ) { # A right parenthesis should be followed by a right square bracket, which itself is a token. # Append the next character and proceed. $token .= shift @{$chars}; } elsif ( $char eq $FULL_STOP ) { # A full stop (i.e. a period, '.') may be the child operator '.' or the recursive operator '..' $token .= shift @{$chars} if $chars->[0] eq $FULL_STOP; } # If we've assembled an operator, we're done. last if $OPERATORS{$token}; # Similarly, if the next character is an operator, we're done last if $OPERATORS{ $chars->[0] }; } return $token; } 1; __END__ =pod =encoding UTF-8 =head1 NAME JSON::Path::Tokenizer - Helper class for JSON::Path::Evaluator. Do not call directly. =head1 VERSION version 0.431 =head1 AUTHOR Kit Peters =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut JSON-Path-0.431/lib/JSON/Path/Evaluator.pm0000644000175000017500000007014014004641374016416 0ustar tooktookpackage JSON::Path::Evaluator; $JSON::Path::Evaluator::VERSION = '0.431'; use strict; use warnings; use 5.008; # ABSTRACT: A module that recursively evaluates JSONPath expressions with native support for Javascript-style filters use Carp; use Carp::Assert qw(assert); use Exporter::Tiny (); use JSON::MaybeXS; use JSON::Path::Constants qw(:operators :symbols); use JSON::Path::Tokenizer qw(tokenize); use List::Util qw/pairs/; use Readonly; use Safe; use Scalar::Util qw/looks_like_number blessed refaddr/; use Storable qw/dclone/; use Sys::Hostname qw/hostname/; use Try::Tiny; # VERSION use base q(Exporter); our $AUTHORITY = 'cpan:POPEFELIX'; our @EXPORT_OK = qw/ evaluate_jsonpath /; Readonly my $OPERATOR_IS_TRUE => 'IS_TRUE'; Readonly my $OPERATOR_TYPE_PATH => 1; Readonly my $OPERATOR_TYPE_COMPARISON => 2; Readonly my %OPERATORS => ( $TOKEN_ROOT => $OPERATOR_TYPE_PATH, # $ $TOKEN_CURRENT => $OPERATOR_TYPE_PATH, # @ $TOKEN_CHILD => $OPERATOR_TYPE_PATH, # . OR [] $TOKEN_RECURSIVE => $OPERATOR_TYPE_PATH, # .. $TOKEN_ALL => $OPERATOR_TYPE_PATH, # * $TOKEN_FILTER_OPEN => $OPERATOR_TYPE_PATH, # ?( $TOKEN_SCRIPT_OPEN => $OPERATOR_TYPE_PATH, # ( $TOKEN_FILTER_SCRIPT_CLOSE => $OPERATOR_TYPE_PATH, # ) $TOKEN_SUBSCRIPT_OPEN => $OPERATOR_TYPE_PATH, # [ $TOKEN_SUBSCRIPT_CLOSE => $OPERATOR_TYPE_PATH, # ] $TOKEN_UNION => $OPERATOR_TYPE_PATH, # , $TOKEN_ARRAY_SLICE => $OPERATOR_TYPE_PATH, # [ start:end:step ] $TOKEN_SINGLE_EQUAL => $OPERATOR_TYPE_COMPARISON, # = $TOKEN_DOUBLE_EQUAL => $OPERATOR_TYPE_COMPARISON, # == $TOKEN_TRIPLE_EQUAL => $OPERATOR_TYPE_COMPARISON, # === $TOKEN_GREATER_THAN => $OPERATOR_TYPE_COMPARISON, # > $TOKEN_LESS_THAN => $OPERATOR_TYPE_COMPARISON, # < $TOKEN_NOT_EQUAL => $OPERATOR_TYPE_COMPARISON, # != $TOKEN_GREATER_EQUAL => $OPERATOR_TYPE_COMPARISON, # >= $TOKEN_LESS_EQUAL => $OPERATOR_TYPE_COMPARISON, # <= ); Readonly my $ASSERT_ENABLE => $ENV{ASSERT_ENABLE}; sub new { my $class = shift; my %args = ref $_[0] eq 'HASH' ? %{ $_[0] } : @_; my $self = {}; for my $key (qw/root expression/) { croak qq{Missing required argument '$key' in constructor} unless $args{$key}; $self->{$key} = $args{$key}; } $self->{want_ref} = $args{want_ref} || 0; $self->{_calling_context} = $args{_calling_context} || 0; my $script_engine = $args{script_engine} ? $args{script_engine} : $self->{expression} =~ /\$_/ ? 'perl' : undef; $self->{script_engine} = $script_engine || 'PseudoJS'; bless $self, $class; return $self; } sub evaluate_jsonpath { my ( $json_object, $expression, %args ) = @_; if ( !ref $json_object ) { try { $json_object = decode_json($json_object); } catch { croak qq{Unable to decode $json_object as JSON: $_}; } } my $want_ref = delete $args{want_ref} || 0; my $want_path = delete $args{want_path} || 0; my $self = __PACKAGE__->new( root => $json_object, expression => $expression, _calling_context => wantarray ? 'ARRAY' : 'SCALAR', %args ); return $self->evaluate( $expression, want_ref => $want_ref, want_path => $want_path ); } sub evaluate { my ( $self, $expression, %args ) = @_; my $json_object = $self->{root}; my $token_stream = [ tokenize($expression) ]; shift @{$token_stream} if $token_stream->[0] eq $TOKEN_ROOT; shift @{$token_stream} if $token_stream->[0] eq $TOKEN_CHILD; if ( $args{want_path} ) { my %reftable = $self->_reftable_walker($json_object); my @refs = $self->_evaluate( $json_object, dclone $token_stream, 1 ); my @paths; for my $ref (@refs) { my $refaddr = ref ${$ref} ? refaddr ${$ref} : refaddr $ref; push @paths, $reftable{$refaddr}; } return @paths; } my @ret = $self->_evaluate( $json_object, $token_stream, $args{want_ref} ); return @ret; } sub _reftable_walker { my ( $self, $json_object, $base_path ) = @_; $base_path = defined $base_path ? $base_path : '$'; $json_object = defined $json_object ? $json_object : $self->root; my @entries = ( refaddr $json_object => $base_path ); if ( _arraylike($json_object) ) { for ( 0 .. $#{$json_object} ) { my $path = sprintf q{%s['%d']}, $base_path, $_; if ( ref $json_object->[$_] ) { push @entries, $self->_reftable_walker( $json_object->[$_], $path ); } else { push @entries, refaddr \( $json_object->[$_] ) => $path; } } } elsif ( _hashlike($json_object) ) { for my $index ( keys %{$json_object} ) { my $path = sprintf q{%s['%s']}, $base_path, $index; if ( ref $json_object->{$index} ) { push @entries, $self->_reftable_walker( $json_object->{$index}, $path ); } else { push @entries, refaddr \( $json_object->{$index} ) => $path; } } } return @entries; } sub _evaluate { # This assumes that the token stream is syntactically valid my ( $self, $obj, $token_stream, $want_ref ) = @_; return unless ref $obj; $token_stream = defined $token_stream ? $token_stream : []; while ( defined( my $token = shift @{$token_stream} ) ) { next if $token eq $TOKEN_CURRENT; next if $token eq $TOKEN_CHILD; if ( $token eq $TOKEN_FILTER_OPEN ) { my $filter_expression = shift @{$token_stream}; my $closing_token = shift @{$token_stream}; assert( $closing_token eq $TOKEN_FILTER_SCRIPT_CLOSE, q{Closing token seen} ) if $ASSERT_ENABLE; # Find all indices matching the filter expression. This modifies $token_stream my @matching_indices = $self->_process_filter( $obj, $filter_expression ); if ( !@{$token_stream} ) { my @got = map { _get( $obj, $_ ) } @matching_indices; return $want_ref ? @got : map { ${$_} } @got; } else { return map { $self->_evaluate( _get( $obj, $_ ), dclone($token_stream), $want_ref ) } @matching_indices; } } elsif ( $token eq $TOKEN_RECURSIVE ) { # Sweet Jesus, Pooh, that's not honey! You're eating Sweet Jesus, Pooh, that's not honey! You're eating... my $index = shift @{$token_stream}; my @matched; if ( $index eq $TOKEN_FILTER_OPEN ) { my $filter_expression = shift @{$token_stream}; my $closing_token = shift @{$token_stream}; assert( $closing_token eq $TOKEN_FILTER_SCRIPT_CLOSE, q{Closing token seen} ) if $ASSERT_ENABLE; return $self->_filter_recursive( $obj, $filter_expression, $want_ref ); } @matched = _match_recursive( $obj, $index, $want_ref ); if ( !@{$token_stream} ) { return @matched; } return map { $self->_evaluate( $_, dclone($token_stream), $want_ref ) } @matched; } else { my $index; if ( $token eq $TOKEN_SUBSCRIPT_OPEN ) { $index = shift @{$token_stream}; my $closing_token = shift @{$token_stream}; assert $closing_token eq $TOKEN_SUBSCRIPT_CLOSE if $ASSERT_ENABLE; } else { $index = $token; } assert( !$OPERATORS{$index}, qq{"$index" is not an operator} ) if $index ne $TOKEN_ALL; assert( !ref $index, q{Index is a scalar} ) if $ASSERT_ENABLE; my (@got) = _get( $obj, $index, create_key => $want_ref ); # This always returns a ref if ( !@{$token_stream} ) { return $want_ref ? @got : map { ${$_} } @got; } else { return map { $self->_evaluate( ${$_}, dclone($token_stream), $want_ref ) } @got; } } } } sub _process_filter { my ( $self, $obj, $filter_expression ) = @_; my @matching_indices; if ( $self->{script_engine} eq 'PseudoJS' ) { @matching_indices = $self->_process_pseudo_js( $obj, $filter_expression ); } elsif ( $self->{script_engine} eq 'perl' ) { @matching_indices = $self->_process_perl( $obj, $filter_expression ); } else { croak qq{Unsupported script engine "$self->{script_engine}"}; } return @matching_indices; } # This _always_ has to return a ref so that when it's called from evaluate( ... , want_ref => 1) # So that we can return a ref into the object (e.g. for use as an lvalue), even when the path points # to a scalar (which will of course be copied). # # I.E.: for { foo => 'bar' }, we always want \( foo->{bar} ) so that # JSON::Path->new('$.foo')->value($obj) = 'baz' works like it oughtta. sub _get { my ( $object, $index, %args ) = @_; assert( _hashlike($object) || _arraylike($object), 'Object is a hashref or an arrayref' ) if $ASSERT_ENABLE; my $create_key = $args{create_key}; # When want_ref is passed to _evaluate(), it will return a reference to whatever was matched. # If what was matched is itself a ref (e.g. an arrayref), _evaluate() will return a ref of # type 'REF'. if ( ref $object eq 'REF' ) { $object = ${$object}; } if ( $index eq $TOKEN_ALL ) { if ( _hashlike($object) ) { return map { \($_) } values %{$object}; } else { return map { \($_) } @{$object}; } } else { my @indices; if ( $index =~ /$TOKEN_ARRAY_SLICE/ ) { my $length = _hashlike($object) ? scalar values %{$object} : scalar @{$object}; @indices = _slice( $index, $length ); } elsif ( $index =~ /$TOKEN_UNION/ ) { @indices = split /$TOKEN_UNION/, $index; } else { @indices = ($index); } if ( _hashlike($object) ) { if ($create_key) { return map { \( $object->{$_} ) } @indices; } else { my @ret; for my $index (@indices) { push @ret, \( $object->{$index} ) if exists $object->{$index}; } return @ret; } } else { my @numeric_indices = grep { looks_like_number($_) } @indices; if ($create_key) { return map { \( $object->[$_] ) } @numeric_indices; } else { my @ret; for my $index (@numeric_indices) { push @ret, \( $object->[$index] ) if exists $object->[$index]; } return @ret; } } } } sub _indices { my $object = shift; return _hashlike($object) ? keys %{$object} : _arraylike($object) ? ( 0 .. $#{$object} ) : (); } sub _hashlike { my $object = shift; return ( ref $object eq 'HASH' || ( blessed $object && $object->can('typeof') && $object->typeof eq 'HASH' ) ); } sub _arraylike { my $object = shift; return ( ref $object eq 'ARRAY' || ( blessed $object && $object->can('typeof') && $object->typeof eq 'ARRAY' ) ); } sub _get_token { my $token_stream = shift; my $token = shift @{$token_stream}; return unless defined $token; if ( $token eq $TOKEN_SUBSCRIPT_OPEN ) { my @substream; my $close_seen; while ( defined( my $token = shift @{$token_stream} ) ) { if ( $token eq $TOKEN_SUBSCRIPT_CLOSE ) { $close_seen = 1; last; } push @substream, $token; } assert($close_seen) if $ASSERT_ENABLE; if ( grep { $_ eq $TOKEN_ARRAY_SLICE } @substream ) { # There are five valid cases: # # n:m -> n:m:1 # n:m:s -> n:m:s # :m -> 0:m:1 # ::s -> 0:-1:s # n: -> n:-1:1 if ( $substream[0] eq $TOKEN_ARRAY_SLICE ) { unshift @substream, undef; } no warnings qw/uninitialized/; if ( $substream[2] eq $TOKEN_ARRAY_SLICE ) { @substream = ( @substream[ ( 0, 1 ) ], undef, @substream[ ( 2 .. $#substream ) ] ); } use warnings qw/uninitialized/; my ( $start, $end, $step ); $start = $substream[0] // 0; $end = $substream[2] // -1; $step = $substream[4] // 1; return { slice => [ $start, $end, $step ] }; } elsif ( grep { $_ eq $TOKEN_UNION } @substream ) { my @union = grep { $_ ne $TOKEN_UNION } @substream; return { union => \@union }; } return $substream[0]; } return $token; } # See http://wiki.ecmascript.org/doku.php?id=proposals:slice_syntax # # in particular, for the slice [n:m], m is *one greater* than the last index to slice. # This means that the slice [3:5] will return indices 3 and 4, but *not* 5. sub _slice { my ( $index, $length ) = @_; my ( $start, $end, $step ) = split /$TOKEN_ARRAY_SLICE/, $index, 3; if ( !defined($start) || $start eq '' ) { $start = 0; } if ( !defined($end) || $end eq '' ) { $end = -1; } if ( !defined($step) || $step eq '' ) { $step = 1; } $start = ( $length - 1 ) if $start == -1; $end = $length if $end == -1; my @indices; if ( $step < 0 ) { @indices = grep { %_ % -$step == 0 } reverse( $start .. ( $end - 1 ) ); } else { @indices = grep { $_ % $step == 0 } ( $start .. ( $end - 1 ) ); } return @indices; } sub _match_recursive { my ( $obj, $index, $want_ref ) = @_; my @match; # Fix for RT #122529. # # Consider the expression "$..foo..bar", evaluated with respect to the JSON "{"foo":{"bar":"baz"}}". # # The first term to be evaluated in the expression is "$..foo". If want_ref is passed to evaluate(), # this will return a REF reference. In that case we must first dereference it to get the object that # we will evaluate "..bar" with respect to. if ( ref $obj eq 'REF' ) { $obj = ${$obj}; } if ( _arraylike($obj) ) { if ( looks_like_number($index) && exists $obj->[$index] ) { push @match, $want_ref ? \( $obj->[$index] ) : $obj->[$index]; } for ( 0 .. $#{$obj} ) { next unless ref $obj->[$_]; push @match, _match_recursive( $obj->[$_], $index, $want_ref ); } } elsif ( _hashlike($obj) ) { if ( exists $obj->{$index} ) { push @match, $want_ref ? \( $obj->{$index} ) : $obj->{$index}; } for my $val ( values %{$obj} ) { next unless ref $val; push @match, _match_recursive( $val, $index, $want_ref ); } } return @match; } sub _filter_recursive { my ( $self, $obj, $expression, $want_ref ) = @_; my @ret; # Evaluate the filter expression for the current object my @matching_indices = $self->_process_filter( $obj, $expression ); for my $index (@matching_indices) { my ($got) = _get( $obj, $index ); push @ret, $want_ref ? $got : ${$got}; } # Evaluate the filter expression for any subordinate objects for my $index ( _indices($obj) ) { my ($got) = _get( $obj, $index ); $got = ${$got}; # _get will always return a reference. We want the value, so dereference it next unless ref $got; push @ret, $self->_filter_recursive( $got, $expression, $want_ref ); } return @ret; } sub _process_pseudo_js { my ( $self, $object, $expression ) = @_; my ( $lhs, $operator, $rhs ) = _parse_psuedojs_expression($expression); my (@token_stream) = tokenize($lhs); my $index; my @lhs; if ( _hashlike($object) ) { @lhs = map { $self->_evaluate( $_, [@token_stream] ) } values %{$object}; } elsif ( _arraylike($object) ) { for my $value ( @{$object} ) { my ($got) = $self->_evaluate( $value, [@token_stream] ); push @lhs, $got; } } # get indexes that pass compare() my @matching; for ( 0 .. $#lhs ) { my $val = $lhs[$_]; push @matching, $_ if _compare( $operator, $val, $rhs ); } return @matching; } sub _parse_psuedojs_expression { my $expression = shift; my @parts; my ( $lhs, $operator, $rhs ); # The operator could be '=', '!=', '==', '===', '<=', or '>=' if ( $expression =~ /$EQUAL_SIGN/ ) { my $position = index( $expression, '=' ); if ( substr( $expression, $position + 1, 1 ) eq $EQUAL_SIGN ) { # could be '==' or '===' if ( substr( $expression, $position + 2, 1 ) eq $EQUAL_SIGN ) { # === $operator = $TOKEN_TRIPLE_EQUAL; } else { $operator = $TOKEN_DOUBLE_EQUAL; } } else { my $preceding_char = substr( $expression, $position - 1, 1 ); if ( $preceding_char eq $GREATER_THAN_SIGN ) { $operator = $TOKEN_GREATER_EQUAL; } elsif ( $preceding_char eq $LESS_THAN_SIGN ) { $operator = $TOKEN_LESS_EQUAL; } elsif ( $preceding_char eq $EXCLAMATION_MARK ) { $operator = $TOKEN_NOT_EQUAL; } else { $operator = $TOKEN_SINGLE_EQUAL; } } ( $lhs, $rhs ) = split /$operator/, $expression, 2; } else { for ( grep { $OPERATORS{$_} eq $OPERATOR_TYPE_COMPARISON } keys %OPERATORS ) { next if /$EQUAL_SIGN/; if ( $expression =~ /$_/ ) { ( $lhs, $rhs ) = split /$_/, $expression, 2; $operator = $_; last; } } } # FIXME: RHS is assumed to be a single value. This isn't necessarily a safe assumption. if ($operator) { $rhs = _normalize( $rhs || '' ); $lhs = _normalize($lhs); } else { $operator = $OPERATOR_IS_TRUE; $lhs = $expression; } return ( $lhs, $operator, $rhs ); } sub _normalize { my $string = shift; # NB: Stripping spaces *before* stripping quotes allows the caller to quote spaces in an index. # So an index of 'foo ' will be correctly normalized as 'foo', but '"foo "' will normalize to 'foo '. $string =~ s/\s+$//; # trim trailing spaces $string =~ s/^\s+//; # trim leading spaces $string =~ s/^['"](.+)['"]$/$1/; # Strip quotes from index return $string; } sub _process_perl { my ( $self, $object, $code ) = @_; my $cpt = Safe->new; $cpt->permit_only( ':base_core', qw/padsv padav padhv padany rv2gv/ ); ${ $cpt->varglob('root') } = dclone( $self->{root} ); my @matching; if ( _hashlike($object) ) { for my $index ( keys %{$object} ) { local $_ = $object->{$index}; my $ret = $cpt->reval($code); croak qq{Error in filter: $@} if $@; push @matching, $index if $ret; } } else { for my $index ( 0 .. $#{$object} ) { local $_ = $object->[$index]; my $ret = $cpt->reval($code); croak qq{Error in filter: $@} if $@; push @matching, $index if $ret; } } return @matching; } sub _compare { my ( $operator, $lhs, $rhs ) = @_; no warnings qw/uninitialized/; if ( $operator eq $OPERATOR_IS_TRUE ) { return $lhs ? 1 : 0; } my $use_numeric = looks_like_number($lhs) && looks_like_number($rhs); if ( $operator eq '=' || $operator eq '==' || $operator eq '===' ) { return $use_numeric ? ( $lhs == $rhs ) : $lhs eq $rhs; } if ( $operator eq '<' ) { return $use_numeric ? ( $lhs < $rhs ) : $lhs lt $rhs; } if ( $operator eq '>' ) { return $use_numeric ? ( $lhs > $rhs ) : $lhs gt $rhs; } if ( $operator eq '<=' ) { return $use_numeric ? ( $lhs <= $rhs ) : $lhs le $rhs; } if ( $operator eq '>=' ) { return $use_numeric ? ( $lhs >= $rhs ) : $lhs ge $rhs; } if ( $operator eq '!=' || $operator eq '!==' ) { return $use_numeric ? ( $lhs != $rhs ) : $lhs ne $rhs; } use warnings qw/uninitialized/; } 1; __END__ =pod =encoding UTF-8 =head1 NAME JSON::Path::Evaluator - A module that recursively evaluates JSONPath expressions with native support for Javascript-style filters =head1 VERSION version 0.431 =head1 SYNOPSIS use JSON::MaybeXS qw/decode_json/; # Or whatever JSON thing you like. I won't judge. use JSON::Path::Evaluator qw/evaluate_jsonpath/; my $obj = decode_json(q( { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } )); my @fiction = evaluate_jsonpath( $obj, q{$..book[?(@.category == "fiction")]}); # @fiction = ( # { category => "fiction", # author => "Evelyn Waugh", # title => "Sword of Honour", # price => 12.99 # }, # { category => "fiction", # author => "Herman Melville", # title => "Moby Dick", # isbn => "0-553-21311-3", # price => 8.99 # }, # { category => "fiction", # author => "J. R. R. Tolkien", # title => "The Lord of the Rings", # isbn => "0-395-19395-8", # price => 22.99 # } # ); =head1 METHODS =head2 new Constructor for the object-oriented interface to this module. Arguments may be specified in a hash or a hashref. Args: =over 4 =item root Required. JSONPath expressions will be evaluated with respect to this. Must be a hashref or an arrayref. =item expression JSONPath expression to evaluate =item want_ref Set this to true if you want a reference to the thing the JSONPath expression matches, rather than the value of said thing. Useful if you want to use this to modify hashrefs / arrayrefs in place. =item script_engine Defaults to "PseudoJS", which is my clever name for a subset of Javascript-B operators for Boolean expressions. See L. You may also specify "perl" here, in which case the filter will be treated as Perl code. See L. =back =head2 evaluate_jsonpath Evaluate a JSONPath expression on the given object. CLASS METHOD. Args: =over 4 =item $json_object JSON object for which the expression will be evaluated. If this is a scalar, it will be treated as a JSON string and parsed into the appropriate Perl data structure first. =item $expression JSONPath expression to evaluate on the object. =item %args Misc. arguments to this method. Currently the only supported argument is 'want_ref' - set this to true in order to return a reference to the matched portion of the object, rather than the value of that matched portion. =back =head2 evaluate Evaluate a JSONPath expression on the object passed to the constructor. OBJECT METHOD. Args: =over 4 =item $expression JSONPath expression to evaluate on the object. =item %args Misc. arguments to this method. Supported keys: =over 4 =item want_ref Set this to true in order to return a reference to the matched portion of the object, rather than the value of the matched portion. =item want_path Set this to true in order to return the canonical path(s) to the elements matching the expression. =back =back =head1 JSONPath This code implements the JSONPath specification at L. JSONPath is a tool, similar to XPath for XML, that allows one to construct queries to pick out parts of a JSON structure. =head2 JSONPath Expressions From the spec: "JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document. Since a JSON structure is usually anonymous and doesn't necessarily have a "root member object" JSONPath assumes the abstract name $ assigned to the outer level object." Note that in JSONPath square brackets operate on the object or array addressed by the previous path fragment. Indices always start by 0. =head2 Operators =over 4 =item $ the root object/element =item @ the current object/element =item . or [] child operator =item .. recursive descent. JSONPath borrows this syntax from E4X. =item '*' (literal asterisk) wildcard. All objects/elements regardless their names. =item [] subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator. =item [,] Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set. =item [start:end:step] array slice operator borrowed from ES4. =item ?() applies a filter (script) expression. See L. =item () script expression, using the underlying script engine. Handled the same as "?()". =back =head2 Filtering Filters are the most powerful feature of JSONPath. They allow the caller to retrieve data conditionally, similar to Perl's C operator. Filters are specified using the '?(' token, terminated by ')'. Anything in between these two tokens is treated as a filter expression. Filter expressions must return a boolean value. =head3 Filtering with PseudoJS By default, this module uses a limited subset of Javascript expressions to evaluate filters. Using this script engine, specify the filter in the form " ", or "". This latter case will be evaluated as " is true". must be a valid JSONPath expression. must be a scalar value; comparison of two JSONPath expressions is not supported at this time. Example: Using the JSON in L above and the JSONPath expression C<$..book[?(@.category == "fiction")]>, the filter expression C<@.category == "fiction"> will match all values having a value of "fiction" for the key "category". =head2 Filtering with Perl When the script engine is set to "perl", filter Using the JSON in L above and the JSONPath expression C<$..book[?(@.category == "fiction")]>, This is understandably dangerous. Although steps have been taken (Perl expressions are evaluated using L and a limited set of permitted opcodes) to reduce the risk, callers should be aware of the risk when using filters. When filtering in Perl, there are some differences between the JSONPath spec and this implementation. =over 4 =item * JSONPath uses the token '$' to refer to the root node. As this is not valid Perl, this should be replaced with '$root' in a filter expression. =item * JSONPath uses the token '@' to refer to the current node. This is also not valid Perl. Use '$_' instead. =back =head1 AUTHOR Kit Peters =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut JSON-Path-0.431/lib/JSON/Path/Constants.pm0000644000175000017500000000737614004641374016443 0ustar tooktookuse strict; use warnings; use 5.008; package JSON::Path::Constants; $JSON::Path::Constants::VERSION = '0.431'; # ABSTRACT: Constants used in the JSON::Path distribution # VERSION use Readonly; use Exporter::Easy ( TAGS => [ symbols => [ '$DOLLAR_SIGN', '$COMMERCIAL_AT', '$FULL_STOP', '$LEFT_SQUARE_BRACKET', '$RIGHT_SQUARE_BRACKET', '$ASTERISK', '$COLON', '$LEFT_PARENTHESIS', '$RIGHT_PARENTHESIS', '$COMMA', '$QUESTION_MARK', '$EQUAL_SIGN', '$EXCLAMATION_MARK', '$GREATER_THAN_SIGN', '$LESS_THAN_SIGN', '$QUOTATION_MARK', '$APOSTROPHE' ], operators => [ '$TOKEN_ROOT', '$TOKEN_CURRENT', '$TOKEN_CHILD', '$TOKEN_RECURSIVE', '$TOKEN_ALL', '$TOKEN_FILTER_OPEN', '$TOKEN_SCRIPT_OPEN', '$TOKEN_FILTER_SCRIPT_CLOSE', '$TOKEN_SUBSCRIPT_OPEN', '$TOKEN_SUBSCRIPT_CLOSE', '$TOKEN_UNION', '$TOKEN_ARRAY_SLICE', '$TOKEN_SINGLE_EQUAL', '$TOKEN_DOUBLE_EQUAL', '$TOKEN_TRIPLE_EQUAL', '$TOKEN_GREATER_THAN', '$TOKEN_LESS_THAN', '$TOKEN_NOT_EQUAL', '$TOKEN_GREATER_EQUAL', '$TOKEN_LESS_EQUAL', ], ] ); Readonly our $QUOTATION_MARK => q{"}; Readonly our $APOSTROPHE => q{'}; Readonly our $DOLLAR_SIGN => '$'; Readonly our $COMMERCIAL_AT => '@'; Readonly our $FULL_STOP => '.'; Readonly our $LEFT_SQUARE_BRACKET => '['; Readonly our $RIGHT_SQUARE_BRACKET => ']'; Readonly our $ASTERISK => '*'; Readonly our $COLON => ':'; Readonly our $LEFT_PARENTHESIS => '('; Readonly our $RIGHT_PARENTHESIS => ')'; Readonly our $COMMA => ','; Readonly our $QUESTION_MARK => '?'; Readonly our $EQUAL_SIGN => '='; Readonly our $EXCLAMATION_MARK => '!'; Readonly our $GREATER_THAN_SIGN => '>'; Readonly our $LESS_THAN_SIGN => '<'; Readonly our $TOKEN_ROOT => $DOLLAR_SIGN; Readonly our $TOKEN_CURRENT => $COMMERCIAL_AT; Readonly our $TOKEN_CHILD => $FULL_STOP; Readonly our $TOKEN_RECURSIVE => $FULL_STOP . $FULL_STOP; Readonly our $TOKEN_ALL => $ASTERISK; Readonly our $TOKEN_FILTER_OPEN => $LEFT_SQUARE_BRACKET . $QUESTION_MARK . $LEFT_PARENTHESIS; Readonly our $TOKEN_SCRIPT_OPEN => $LEFT_SQUARE_BRACKET . $LEFT_PARENTHESIS; Readonly our $TOKEN_FILTER_SCRIPT_CLOSE => $RIGHT_PARENTHESIS . $RIGHT_SQUARE_BRACKET; Readonly our $TOKEN_SUBSCRIPT_OPEN => $LEFT_SQUARE_BRACKET; Readonly our $TOKEN_SUBSCRIPT_CLOSE => $RIGHT_SQUARE_BRACKET; Readonly our $TOKEN_UNION => $COMMA; Readonly our $TOKEN_ARRAY_SLICE => $COLON; Readonly our $TOKEN_SINGLE_EQUAL => $EQUAL_SIGN; Readonly our $TOKEN_DOUBLE_EQUAL => $EQUAL_SIGN . $EQUAL_SIGN; Readonly our $TOKEN_TRIPLE_EQUAL => $EQUAL_SIGN . $EQUAL_SIGN . $EQUAL_SIGN; Readonly our $TOKEN_GREATER_THAN => $GREATER_THAN_SIGN; Readonly our $TOKEN_LESS_THAN => $LESS_THAN_SIGN; Readonly our $TOKEN_NOT_EQUAL => $EXCLAMATION_MARK . $EQUAL_SIGN; Readonly our $TOKEN_GREATER_EQUAL => $GREATER_THAN_SIGN . $EQUAL_SIGN; Readonly our $TOKEN_LESS_EQUAL => $LESS_THAN_SIGN . $EQUAL_SIGN; 1; __END__ =pod =encoding UTF-8 =head1 NAME JSON::Path::Constants - Constants used in the JSON::Path distribution =head1 VERSION version 0.431 =head1 AUTHOR Kit Peters =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2021 by Kit Peters. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut JSON-Path-0.431/t/0000775000175000017500000000000014004641374012146 5ustar tooktookJSON-Path-0.431/t/00-report-prereqs.t0000644000175000017500000001345214004641374015545 0ustar tooktook#!perl use strict; use warnings; # This test was generated by Dist::Zilla::Plugin::Test::ReportPrereqs 0.028 use Test::More tests => 1; use ExtUtils::MakeMaker; use File::Spec; # from $version::LAX my $lax_version_re = qr/(?: undef | (?: (?:[0-9]+) (?: \. | (?:\.[0-9]+) (?:_[0-9]+)? )? | (?:\.[0-9]+) (?:_[0-9]+)? ) | (?: v (?:[0-9]+) (?: (?:\.[0-9]+)+ (?:_[0-9]+)? )? | (?:[0-9]+)? (?:\.[0-9]+){2,} (?:_[0-9]+)? ) )/x; # hide optional CPAN::Meta modules from prereq scanner # and check if they are available my $cpan_meta = "CPAN::Meta"; my $cpan_meta_pre = "CPAN::Meta::Prereqs"; my $HAS_CPAN_META = eval "require $cpan_meta; $cpan_meta->VERSION('2.120900')" && eval "require $cpan_meta_pre"; ## no critic # Verify requirements? my $DO_VERIFY_PREREQS = 1; sub _max { my $max = shift; $max = ( $_ > $max ) ? $_ : $max for @_; return $max; } sub _merge_prereqs { my ($collector, $prereqs) = @_; # CPAN::Meta::Prereqs object if (ref $collector eq $cpan_meta_pre) { return $collector->with_merged_prereqs( CPAN::Meta::Prereqs->new( $prereqs ) ); } # Raw hashrefs for my $phase ( keys %$prereqs ) { for my $type ( keys %{ $prereqs->{$phase} } ) { for my $module ( keys %{ $prereqs->{$phase}{$type} } ) { $collector->{$phase}{$type}{$module} = $prereqs->{$phase}{$type}{$module}; } } } return $collector; } my @include = qw( ); my @exclude = qw( ); # Add static prereqs to the included modules list my $static_prereqs = do './t/00-report-prereqs.dd'; # Merge all prereqs (either with ::Prereqs or a hashref) my $full_prereqs = _merge_prereqs( ( $HAS_CPAN_META ? $cpan_meta_pre->new : {} ), $static_prereqs ); # Add dynamic prereqs to the included modules list (if we can) my ($source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; my $cpan_meta_error; if ( $source && $HAS_CPAN_META && (my $meta = eval { CPAN::Meta->load_file($source) } ) ) { $full_prereqs = _merge_prereqs($full_prereqs, $meta->prereqs); } else { $cpan_meta_error = $@; # capture error from CPAN::Meta->load_file($source) $source = 'static metadata'; } my @full_reports; my @dep_errors; my $req_hash = $HAS_CPAN_META ? $full_prereqs->as_string_hash : $full_prereqs; # Add static includes into a fake section for my $mod (@include) { $req_hash->{other}{modules}{$mod} = 0; } for my $phase ( qw(configure build test runtime develop other) ) { next unless $req_hash->{$phase}; next if ($phase eq 'develop' and not $ENV{AUTHOR_TESTING}); for my $type ( qw(requires recommends suggests conflicts modules) ) { next unless $req_hash->{$phase}{$type}; my $title = ucfirst($phase).' '.ucfirst($type); my @reports = [qw/Module Want Have/]; for my $mod ( sort keys %{ $req_hash->{$phase}{$type} } ) { next if $mod eq 'perl'; next if grep { $_ eq $mod } @exclude; my $file = $mod; $file =~ s{::}{/}g; $file .= ".pm"; my ($prefix) = grep { -e File::Spec->catfile($_, $file) } @INC; my $want = $req_hash->{$phase}{$type}{$mod}; $want = "undef" unless defined $want; $want = "any" if !$want && $want == 0; my $req_string = $want eq 'any' ? 'any version required' : "version '$want' required"; if ($prefix) { my $have = MM->parse_version( File::Spec->catfile($prefix, $file) ); $have = "undef" unless defined $have; push @reports, [$mod, $want, $have]; if ( $DO_VERIFY_PREREQS && $HAS_CPAN_META && $type eq 'requires' ) { if ( $have !~ /\A$lax_version_re\z/ ) { push @dep_errors, "$mod version '$have' cannot be parsed ($req_string)"; } elsif ( ! $full_prereqs->requirements_for( $phase, $type )->accepts_module( $mod => $have ) ) { push @dep_errors, "$mod version '$have' is not in required range '$want'"; } } } else { push @reports, [$mod, $want, "missing"]; if ( $DO_VERIFY_PREREQS && $type eq 'requires' ) { push @dep_errors, "$mod is not installed ($req_string)"; } } } if ( @reports ) { push @full_reports, "=== $title ===\n\n"; my $ml = _max( map { length $_->[0] } @reports ); my $wl = _max( map { length $_->[1] } @reports ); my $hl = _max( map { length $_->[2] } @reports ); if ($type eq 'modules') { splice @reports, 1, 0, ["-" x $ml, "", "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s\n", -$ml, $_->[0], $hl, $_->[2]) } @reports; } else { splice @reports, 1, 0, ["-" x $ml, "-" x $wl, "-" x $hl]; push @full_reports, map { sprintf(" %*s %*s %*s\n", -$ml, $_->[0], $wl, $_->[1], $hl, $_->[2]) } @reports; } push @full_reports, "\n"; } } } if ( @full_reports ) { diag "\nVersions for all modules listed in $source (including optional ones):\n\n", @full_reports; } if ( $cpan_meta_error || @dep_errors ) { diag "\n*** WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ***\n"; } if ( $cpan_meta_error ) { my ($orig_source) = grep { -f } 'MYMETA.json', 'MYMETA.yml'; diag "\nCPAN::Meta->load_file('$orig_source') failed with: $cpan_meta_error\n"; } if ( @dep_errors ) { diag join("\n", "\nThe following REQUIRED prerequisites were not satisfied:\n", @dep_errors, "\n" ); } pass('Reported prereqs'); # vim: ts=4 sts=4 sw=4 et: JSON-Path-0.431/t/00-report-prereqs.dd0000644000175000017500000000575514004641374015700 0ustar tooktookdo { my $x = { 'configure' => { 'requires' => { 'ExtUtils::MakeMaker' => '0' } }, 'develop' => { 'requires' => { 'File::Spec' => '0', 'IO::Handle' => '0', 'IPC::Open3' => '0', 'Test::EOL' => '0', 'Test::HasVersion' => '0', 'Test::More' => '0', 'Test::Pod' => '1.41', 'Test::Pod::Coverage' => '0', 'Test::RDF::DOAP::Version' => '0', 'Test::Tabs' => '0', 'XT::Util' => '0' } }, 'runtime' => { 'requires' => { 'Carp' => '0', 'Carp::Assert' => '0', 'Exporter' => '0', 'Exporter::Easy' => '0', 'Exporter::Tiny' => '0', 'JSON::MaybeXS' => '0', 'LV' => '0', 'List::Util' => '1.48', 'Readonly' => '0', 'Safe' => '0', 'Scalar::Util' => '0', 'Storable' => '0', 'Sys::Hostname' => '0', 'Try::Tiny' => '0', 'base' => '0', 'overload' => '0', 'perl' => '5.016', 'strict' => '0', 'warnings' => '0' } }, 'test' => { 'recommends' => { 'CPAN::Meta' => '2.120900' }, 'requires' => { 'ExtUtils::MakeMaker' => '0', 'File::Spec' => '0', 'JSON' => '0', 'JSON::Parse' => '0', 'Test2::V0' => '0', 'Test::Deep' => '0', 'Test::More' => '0', 'Test::Most' => '0', 'Tie::IxHash' => '0', 'perl' => '5.016' } } }; $x; }JSON-Path-0.431/t/02zeroth.t0000644000175000017500000000237014004641374014010 0ustar tooktook =head1 PURPOSE Check the zeroth array element can be selected. =head1 SEE ALSO L. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2011-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use Test::More tests => 6; BEGIN { use_ok('JSON::Path') } use JSON; my $object = { # 'foo' => [ # { 'bar' => 1, }, { 'bar' => 2, }, { 'bar' => 3, }, ] }; my $jpath1 = JSON::Path->new('$.foo[0]'); my @values1 = $jpath1->values( to_json($object) ); is( scalar @values1, 1, 'Only returned a single result.' ); my $jpath2 = JSON::Path->new('$.foo[0,1]'); my @values2 = $jpath2->values( to_json($object) ); is( scalar @values2, 2, 'Returned two results.' ); my $jpath3 = JSON::Path->new('$.foo[1:3]'); my @values3 = $jpath3->values( to_json($object) ); is( scalar @values3, 2, 'Returned two results.' ); my $jpath4 = JSON::Path->new('$.foo[-1:]'); my @values4 = $jpath4->values( to_json($object) ); is( scalar @values4, 1, 'Returned one result.' ); is( $values4[0]->{bar}, 3, 'Correct result.' ); JSON-Path-0.431/t/dots_in_path.t0000644000175000017500000000033514004641374015005 0ustar tooktookuse 5.016; use Test2::V0 '-target' => 'JSON::Path'; my $json = '{ "path.two" : "value.two", "path.one" : "value.one" }'; my $jpath = $CLASS->new('$.path\.one'); is $jpath->value($json), 'value.one'; done_testing; JSON-Path-0.431/t/06lvalue.t0000644000175000017500000000236714004641374013777 0ustar tooktook =head1 PURPOSE Basic tests for some of the lvalue stuff. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use strict; use warnings; use Test::More; use JSON::Path -all; my $person = { name => "Robert", foo => { bar => [ 1, 2, 3 ] } }; my $path = JSON::Path->new('$.name'); $path->value($person) = "Bob"; is_deeply( $person, { name => "Bob", foo => { bar => [ 1, 2, 3 ] } } , q{Setting 'name' changes only the 'name' key and nothing else}); jpath1( $person, '$.name' ) = "Robbie"; jpath1( $person, '$.foo.bar' ) = 12; is_deeply( $person, { name => "Robbie", foo => { bar => 12 } }, q{jpath1() works as lvalue}); $path->value($person) ||= 'Fred'; is $person->{name}, 'Robbie', q{lvalue works with ||=}; $path = JSON::Path->new('$.quux'); $path->value($person) = 'alpha'; is $person->{quux}, 'alpha', q{lvalue will create keys not previously extant}; $path = JSON::Path->new('$.quuy'); $path->value($person) ||= 'beta'; is $person->{quuy}, 'beta', q{lvalue and ||= will create keys not previously extant}; done_testing; JSON-Path-0.431/t/path-construction-failure.t0000644000175000017500000000231514004641374017443 0ustar tooktookuse Test2::V0 '-target' => 'JSON::Path'; # Test demonstrating RT #122109, "paths method succeeds in search but then fails on path construction" # https://rt.cpan.org/Ticket/Display.html?id=122109 # my $json='{ "4" : { "value_raw" : "European", "value" : "European", "name" : "Ethnicity", "type" : "radio", "id" : 4 }, "1" : { "middle" : "", "first" : "James", "value" : "James Bowery", "last" : "Bowery", "name" : "Name", "type" : "name", "id" : 1 }, "3" : { "value_raw" : "Male", "value" : "Male", "name" : "Gender", "type" : "radio", "id" : 3 }, "2" : { "unix" : 1498176000, "time" : "", "date" : "06/23/2017", "value" : "06/23/2017", "name" : "Birthdate", "type" : "date-time", "id" : 2 }, "5" : { "value" : "jabowery@emailservice.com", "name" : "Email", "type" : "text", "id" : 5 } }'; my $p3 = $CLASS->new( '$.[?($_->{name} eq "Email")]'); my @paths; ok lives { @paths = $p3->paths($json) }, q{paths() did not die} or diag qq{Caught exception: $@}; is \@paths, [ q{$['5']} ], q{paths() produced correct path}; done_testing; JSON-Path-0.431/t/05set.t0000644000175000017500000000362414004641374013276 0ustar tooktook =head1 PURPOSE Exercise C<< JSON::Path::set >>. =head1 SEE ALSO L. =head1 AUTHOR Mitsuhiro Nakamura =head1 COPYRIGHT AND LICENCE Copyright 2013 Mitsuhiro Nakamura. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use strict; use warnings; use Test::More; use JSON::Path -all; use JSON; my $object = from_json(<<'JSON'); { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } JSON my $titles = '$.store.book[*].title'; my $jpath = JSON::Path->new($titles); is_deeply( [ $jpath->values($object) ], [ "Sayings of the Century", "Sword of Honour", "Moby Dick", "The Lord of the Rings", ] ); is( $jpath->set( $object => 'TBD', 2 ), 2, ); is_deeply( [ $jpath->values($object) ], [ "TBD", "TBD", "Moby Dick", "The Lord of the Rings", ], ); my $author = '$.store.book[2].author'; $jpath = JSON::Path->new($author); is( $jpath->value($object), "Herman Melville", ); is( $jpath->set( $object => 'Anon' ), 1, ); is( $jpath->value($object), 'Anon', ); $jpath = JSON::Path->new('$.store.book.0.publisher'); is( $jpath->set( $object, 'Peculiar Publications' ), 1 ); is( $jpath->value( $object ), 'Peculiar Publications' ); done_testing; JSON-Path-0.431/t/07utf8.t0000644000175000017500000000270514004641374013372 0ustar tooktook =head1 PURPOSE Some basic Tests for handling of unicode characters in JSON data. =head1 AUTHOR Heiko Jansen Ehjansen@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2016 Heiko Jansen. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use Test::More tests => 5; BEGIN { use_ok('JSON::Path') } use JSON::MaybeXS; my $data = <<"JSON"; { "store": { "book": [ { "category": "reference", "author": "Randal L. Schwartz", "title": "Einf\xFChrung in Perl", "isbn": "9783868991451", "price": 34.90 }, { "category": "chartest", "author": "\x{61}\x{0300}\x{0320}. u. thor", "title": "Me \x{2661} Unicode", "price": 0.0 } ], "bicycle": { "color": "r\xF6tlich", "price": 19.95 } } } JSON utf8::encode($data); my $object = decode_json($data); my $path1 = JSON::Path->new('$.store.book[0].title'); is( "$path1", '$.store.book[0].title', "overloaded stringification" ); my @results1 = $path1->values($object); is( $results1[0], "Einf\xFChrung in Perl", "basic value result" ); @results1 = $path1->paths($object); is( $results1[0], "\$['store']['book']['0']['title']", "basic path result" ); my $path2 = JSON::Path->new('$.store.book[1].author'); my @results2 = $path2->values($object); is( $results2[0], "\x{61}\x{0300}\x{0320}. u. thor", "basic value result" ); JSON-Path-0.431/t/08context.t0000644000175000017500000000106314004641374014165 0ustar tooktookuse Test::More; use JSON::Path; use JSON; my $object = from_json(<<'JSON'); { "elements": [ { "id": 1 }, { "id": 2 } ], "empty": null } JSON my $path1 = JSON::Path->new('$.elements[*]'); my @arr = $path1->values($object); is_deeply \@arr, [ { id => 1 }, { id => 2 } ], 'multiple values in list context'; my $scal = $path1->values($object); cmp_ok $scal, '==', 2, 'multiple values in scalar context'; my $path2 = JSON::Path->new('$.empty'); ok !!$path2->values($object), 'boolean check for existing null is true'; done_testing(); JSON-Path-0.431/t/01basic.t0000644000175000017500000000455014004641374013557 0ustar tooktook =head1 PURPOSE Some basic JSON Path selection tests, including some using C, checking that its disallowed by default but can be switched on using the C<< $JSON::Path::Safe >> package variable. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2010-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use Test::More; BEGIN { use_ok('JSON::Path') } use JSON; my $object = from_json(<<'JSON'); { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } JSON my $path1 = JSON::Path->new('$.store.book[0].title'); is( "$path1", '$.store.book[0].title', "overloaded stringification" ); my @results1 = $path1->values($object); is( $results1[0], 'Sayings of the Century', "basic value result" ); @results1 = $path1->paths($object); is( $results1[0], "\$['store']['book']['0']['title']", "basic path result" ); my $path2 = JSON::Path->new('$..book[-1:]'); my ($results2) = $path2->values($object); is( ref $results2, 'HASH', "hashref value result" ); is( $results2->{isbn}, "0-395-19395-8", "hashref seems to be correct" ); ok( $JSON::Path::Safe, "safe by default" ); ok( !eval { my $path3 = JSON::Path->new('$..book[?($_->{author} =~ /tolkien/i)]'); my $results3 = $path3->values($object); 1; }, "eval disabled by default" ); $JSON::Path::Safe = 0; my $path3 = JSON::Path->new('$..book[?($_->{author} =~ /tolkien/i)]'); my ($results3) = $path3->values($object); # TODO #is( ref $results3, 'HASH', "dangerous hashref value result" ); #is( $results3->{isbn}, "0-395-19395-8", "dangerous hashref seems to be correct" ); done_testing; JSON-Path-0.431/t/03shortcuts.t0000644000175000017500000000256014004641374014535 0ustar tooktook =head1 PURPOSE Test C and C exported functions. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2012-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use Test::More; use JSON::Path -all; use JSON; my $object = from_json(<<'JSON'); { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } } } JSON my $path1 = '$.store.book[*].title'; is_deeply( [ jpath1( $object, $path1 ) ], ['Sayings of the Century'], ); is_deeply( [ jpath( $object, $path1 ) ], [ 'Sayings of the Century', 'Sword of Honour', 'Moby Dick', 'The Lord of the Rings' ], ); done_testing(); JSON-Path-0.431/t/04map.t0000644000175000017500000000321714004641374013255 0ustar tooktook =head1 PURPOSE Test C exported function. =head1 AUTHOR Toby Inkster Etobyink@cpan.orgE. =head1 COPYRIGHT AND LICENCE Copyright 2012-2013 Toby Inkster. This module is tri-licensed. It is available under the X11 (a.k.a. MIT) licence; you can also redistribute it and/or modify it under the same terms as Perl itself. =cut use Test::More; use JSON::Path -all; use JSON; my $object = from_json(<<'JSON'); { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 }, "boolean": false } } JSON my $path1 = '$.store.book[*].title'; jpath_map { uc $_ } $object, '$.store.book[*].title'; is_deeply( [ jpath1( $object, $path1 ) ], [ map uc, 'Sayings of the Century' ], ); is_deeply( [ jpath( $object, $path1 ) ], [ map uc, 'Sayings of the Century', 'Sword of Honour', 'Moby Dick', 'The Lord of the Rings' ], ); is( JSON::Path->new('$.store.book[*].author')->set( $object => 'Anon', 2 ), 2, ); is_deeply( [ jpath( $object, '$.store.book[*].author' ) ], [ 'Anon', 'Anon', 'Herman Melville', 'J. R. R. Tolkien' ], ); done_testing(); JSON-Path-0.431/t/evaluator/0000775000175000017500000000000014004641374014150 5ustar tooktookJSON-Path-0.431/t/evaluator/tokenize.t0000644000175000017500000000371514004641374016171 0ustar tooktookuse Test2::V0; use JSON::Path::Tokenizer qw(tokenize); my @EXPRESSIONS = ( q{$[1:3:2].foobar} => [qw/$ [ 1:3:2 ] . foobar/], q{$.[0].title} => [qw/$ . [ 0 ] . title/], q{$.store.book[?(@.price < 10)].title} => [ qw/$ . store . book [?(/, '@.price < 10', qw/)] . title/ ], '$.[*].id' => [qw/$ . [ * ] . id/], q{$.[1].title} => [qw/$ . [ 1 ] . title/], q{$..labels[?(@.name==bug)]} => [qw/$ .. labels [?( @.name==bug )]/], q{$.store.book[(@.length-1)].title} => [qw/$ . store . book [( @.length-1 )] . title/], q{$.store.book[?(@.price < 10)].title} => [ qw/$ . store . book [?(/, '@.price < 10', qw/)] . title/ ], q{$.store.book[?(@.price <= 10)].title} => [ qw/$ . store . book [?(/, '@.price <= 10', qw/)] . title/ ], q{$.store.book[?(@.price >= 10)].title} => [ qw/$ . store . book [?(/, '@.price >= 10', qw/)] . title/ ], q{$.store.book[?(@.price === 10)].title} => [ qw/$ . store . book [?(/, '@.price === 10', qw/)] . title/ ], q{$['store']['book'][0]['author']} => [ '$', '[', q(store), ']', '[', q(book), ']', '[', 0, ']', '[', q(author), ']' ], q{$['store']['book'][1]['author']} => [ '$', '[', q(store), ']', '[', q(book), ']', '[', 1, ']', '[', q(author), ']' ], q{$.[*].user[?(@.login == 'laurilehmijoki')]} => [ qw/$ . [ * ] . user [?(/, q{@.login == 'laurilehmijoki'}, ')]' ], q{$.path\.one.two} => [qw/$ . path.one . two/], q{$.'path.one'.two} => [qw/$ . path.one . two/], ); for ( 0 .. ( $#EXPRESSIONS / 2 ) ) { my $expression = $EXPRESSIONS[ $_ * 2 ]; my $expected = $EXPRESSIONS[ $_ * 2 + 1 ]; my $tokens; subtest $expression => sub { ok lives { $tokens = [ tokenize($expression) ] }, q{tokenize() did not die}; is $tokens, $expected, q{Token stream correct}; }; } done_testing; JSON-Path-0.431/t/evaluator/path-construction-fail.t0000644000175000017500000000246514004641374020737 0ustar tooktookuse Test2::V0 '-target' => 'JSON::Path'; # Test demonstrating RT #122109, "paths method succeeds in search but then fails on path construction" # https://rt.cpan.org/Ticket/Display.html?id=122109 # use JSON::Parse 'parse_json'; local $JSON::Path::Safe = 0; my $json = '{ "4" : { "value_raw" : "European", "value" : "European", "name" : "Ethnicity", "type" : "radio", "id" : 4 }, "1" : { "middle" : "", "first" : "James", "value" : "James Bowery", "last" : "Bowery", "name" : "Name", "type" : "name", "id" : 1 }, "3" : { "value_raw" : "Male", "value" : "Male", "name" : "Gender", "type" : "radio", "id" : 3 }, "2" : { "unix" : 1498176000, "time" : "", "date" : "06/23/2017", "value" : "06/23/2017", "name" : "Birthdate", "type" : "date-time", "id" : 2 }, "5" : { "value" : "jabowery@emailservice.com", "name" : "Email", "type" : "text", "id" : 5 } }'; my $json_hash = parse_json($json); my $p3 = $CLASS->new('$.[?($_->{name} eq "Email")]'); my @paths; ok lives { @paths = $p3->paths($json_hash) }, q{paths() did not die} or diag qq{Caught exception: $@}; is \@paths, [q{$['5']}], q{paths() produced correct path}; done_testing; JSON-Path-0.431/t/evaluator/want_path.t0000644000175000017500000000406114004641374016321 0ustar tooktookuse Test2::V0 '-target' => 'JSON::Path::Evaluator'; use JSON::MaybeXS; my $json = q({ "store" : { "book" : [ { "price" : 8.95, "title" : "Sayings of the Century", "author" : "Nigel Rees", "category" : "reference" }, { "price" : 12.99, "title" : "Sword of Honour", "author" : "Evelyn Waugh", "category" : "fiction" }, { "price" : 8.99, "isbn" : "0-553-21311-3", "title" : "Moby Dick", "author" : "Herman Melville", "category" : "fiction" }, { "price" : 22.99, "isbn" : "0-395-19395-8", "title" : "The Lord of the Rings", "author" : "J. R. R. Tolkien", "category" : "fiction" } ], "open_for_the_holidays": false } }); my $obj = decode_json($json); my @expressions = ( q{$..[?(@.price > 10)]} => [ q{$['store']['book']['1']}, q{$['store']['book']['3']}, ], q{$.store.book.0.price} => q{$['store']['book']['0']['price']}, q{$.store.book[?($_->{author} eq "J. R. R. Tolkien")]} => q{$['store']['book']['3']}, q{$.store.book[?($_->{category} eq "fiction")]} => [ q{$['store']['book']['1']}, q{$['store']['book']['2']}, q{$['store']['book']['3']} ], q{$.store.open_for_the_holidays} => q{$['store']['open_for_the_holidays']}, ); do_test(@expressions); done_testing; sub do_test { my @expressions = @_; while ( my $expression = shift @expressions ) { subtest $expression => sub { my $expected = shift @expressions; $expected = [$expected] unless ref $expected eq 'ARRAY'; my @got; ok lives { @got = JSON::Path::Evaluator::evaluate_jsonpath( $json, $expression, want_path => 1 ); }, q{evaluate_jsonpath did not die} or diag qq{Caught exception $@}; is \@got, $expected, qq{"$expression" evaluated correctly}; }; } } JSON-Path-0.431/t/evaluator/paths.t0000644000175000017500000001347714004641374015466 0ustar tooktookuse Test::Most; use Test::Deep; use JSON::MaybeXS qw/encode_json decode_json/; use JSON::Path::Evaluator; use Storable qw(dclone); use Tie::IxHash; my $json = sample_json(); my %data = %{ decode_json($json) }; subtest filter => sub { my @expressions = ( '$..[?(@.price > 10)]' => [ grep { $_->{price} > 10 } @{ $data{store}{book} } ], '$.complex_array[?(@.weight > 10)]' => [ map { dclone $_ } grep { $_->{weight} > 10 } @{ $data{complex_array} } ], '$.complex_array[?($_->{weight} > 10)]' => [ map { dclone $_ } grep { $_->{weight} > 10 } @{ $data{complex_array} } ], '$.complex_array[?(@.type.code=="CODE_ALPHA")]' => [ dclone( ( grep { $_->{type}{code} eq 'CODE_ALPHA' } @{ $data{complex_array} } )[0] ) ], '$.complex_array[?(@.weight > 10)].classification.quux' => [ map { $_->{classification}{quux} } grep { $_->{weight} > 10 } @{ $data{complex_array} } ], '$.complex_array[?(@.quux)]' => [ grep { $_->{quux} } @{ $data{complex_array} } ], ); do_test(@expressions); }; subtest simple => sub { my @expressions = ( '$.nonexistent' => [ ], '$.simple' => [ $data{simple} ], '$.boolean' => [ $data{boolean} ], '$.long_hash.key1.subkey2' => [ $data{long_hash}{key1}{subkey2} ], '$.long_hash.key1' => [ dclone $data{long_hash}{key1} ], q{$.complex_array[0]['foo']} => [ $data{complex_array}[0]{foo} ], '$.multilevel_array.1.0.0' => [ $data{multilevel_array}->[1][0][0] ], '$.multilevel_array.0.1[0]' => [ $data{multilevel_array}->[0][1][0] ], '$.multilevel_array[0][0][1]' => [ $data{multilevel_array}->[0][0][1] ], '$.store.book[0].title' => [ $data{store}{book}->[0]{title} ], '$.array[0]' => [ $data{array}->[0] ], ); do_test(@expressions); }; subtest all => sub { my @expressions = ( '$.*' => [ map { ref $_ ? dclone $_ : $_ } values %data ], '$.store.book[*].title' => [ map { $_->{title} } @{ $data{store}{book} } ], ); do_test(@expressions); }; subtest recursive => sub { my @expressions = ( '$..nonexistent' => [], '$..foo' => [qw/bar baz bak/], '$..complex_array[?(@.weight > 10)].classification.quux' => [ map { $_->{classification}{quux} } grep { $_->{weight} > 10 } @{ $data{complex_array} } ], '$..key2.subkey1' => ['2value1'], '$..book[-1:]' => [ $data{store}{book}->[-1] ], ); do_test(@expressions); }; subtest 'slice and union' => sub { my @expressions = ( '$.array[0,1]' => [ @{ $data{array} }[ ( 0, 1 ) ] ], '$.array[1:3]' => [ @{ $data{array} }[ ( 1 .. 2 ) ] ], '$.array[-1:]' => [ $data{array}->[-1] ], '$.long_hash.key1[subkey1,subkey2]' => [ @{ $data{long_hash}{key1} }{qw/subkey1 subkey2/} ], ); do_test(@expressions); }; done_testing; sub do_test { my @expressions = @_; while ( my $expression = shift @expressions ) { my $expected = shift @expressions; my @got; lives_and { @got = JSON::Path::Evaluator::evaluate_jsonpath( $json, $expression ); cmp_bag( \@got, $expected ); } qq{"$expression" evaluated correctly}; } } sub sample_json { my $data = < sub { plan skip_all => 'This test not requested' if @tests_to_run && !grep { lc($_) eq 'recursive' } @tests_to_run; my @expressions = ( '$..book[-1:]' => single_ref( sub { $_[0]->{store}{book}[-1] } ), '$..foo' => sub { my ( $refs, $obj ) = @_; for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; is ref $ref, 'SCALAR', qq{Reftype $_ OK}; ${$ref} = $expected; is $obj->{complex_array}[$_]{foo}, $expected, qq{Value $_ OK}; } }, '$..nonexistent' => sub { my ( $refs, $obj ) = @_; is scalar @{$refs}, 0, 'Nonexistent recursive path gives nothing back'; }, ); while ( my $expression = shift @expressions ) { my $test = shift @expressions; do_test( $expression, $test ); } }; subtest filtering => sub { if ( @tests_to_run && !grep { lc($_) eq 'filtering' } @tests_to_run ) { plan skip_all => 'This test not requested'; } my @expressions = ( '$.complex_array[?(@.quux)]' => sub { my ( $refs, $obj ) = @_; my @indices = grep { $obj->{complex_array}[$_]{quux} } ( 0 .. $#{ $obj->{complex_array} } ); for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; ${$ref} = $expected; is $obj->{complex_array}[ $indices[$_] ], $expected, q{Value OK}; } }, '$.complex_array[?(@.type.code=="CODE_ALPHA")]' => single_ref( sub { $_[0]->{complex_array}[0] } ), ); while ( my $expression = shift @expressions ) { my $test = shift @expressions; do_test( $expression, $test ); } }; subtest simple => sub { plan skip_all => 'This test not requested' if @tests_to_run && !grep { lc($_) eq 'simple' } @tests_to_run; my @expressions = ( '$.array[-1:]' => single_ref( sub { $_[0]->{array}[-1] } ), '$.simple' => single_ref( sub { $_[0]->{simple} } ), '$.boolean' => single_ref( sub { $_[0]->{boolean} } ), '$.long_hash.key1.subkey2' => single_ref( sub { $_[0]->{long_hash}{key1}{subkey2} } ), '$.multilevel_array.1.0.0' => single_ref( sub { $_[0]->{multilevel_array}[1][0][0] } ), '$.store.book[0].title' => single_ref( sub { $_[0]->{store}{book}[0]{title} } ), '$.array[0]' => single_ref( sub { $_[0]->{array}[0] } ), '$.long_hash.key1' => single_ref( sub { $_[0]->{long_hash}{key1} } ), '$.nonexistent' => sub { my ( $refs, $obj ) = @_; ok exists $obj->{nonexistent}, 'want_ref creates the key'; }, ); while ( my $expression = shift @expressions ) { my $test = shift @expressions; do_test( $expression, $test ); } }; subtest 'union, slice, and all' => sub { plan skip_all => 'This test not requested' if @tests_to_run && !grep { lc($_) eq 'union' } @tests_to_run; my @expressions = ( '$.store.book[*].title' => sub { my ( $refs, $obj ) = @_; for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; is ref $ref, 'SCALAR', qq{Reftype $_ OK}; ${$ref} = $expected; is $obj->{store}{book}[$_]{title}, $expected, qq{Value $_ OK}; } }, '$.long_hash.key1[subkey1,subkey2]' => sub { my ( $refs, $obj ) = @_; for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; is ref $ref, 'SCALAR', qq{Reftype $_ OK}; ${$ref} = $expected; if ( $_ == 0 ) { is $obj->{long_hash}{key1}{subkey1}, $expected, q{Value for 'subkey1' OK}; } else { is $obj->{long_hash}{key1}{subkey2}, $expected, q{Value for 'subkey2' OK}; } } }, '$.array[0,1]' => sub { my ( $refs, $obj ) = @_; for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; is ref $ref, 'SCALAR', qq{Reftype $_ OK}; ${$ref} = $expected; is $obj->{array}[$_], $expected, qq{Value $_ OK}; } }, '$.array[1:3]' => sub { my ( $refs, $obj ) = @_; for ( 0 .. $#{$refs} ) { my $ref = $refs->[$_]; my $expected = int rand 1000; is ref $ref, 'SCALAR', qq{Reftype $_ OK}; ${$ref} = $expected; is $obj->{array}[ $_ + 1 ], $expected, qq{Value $_ OK}; } }, ); while ( my $expression = shift @expressions ) { my $test = shift @expressions; do_test( $expression, $test ); } }; done_testing; sub do_test { my ( $expression, $test ) = @_; my $json = sample_json(); my $obj = decode_json($json); subtest $expression => sub { my @refs; lives_ok { @refs = JSON::Path::Evaluator::evaluate_jsonpath( $obj, $expression, want_ref => 1 ) } q{evaluate() did not die}; $test->( \@refs, $obj ); }; } sub single_ref { my $path = shift; return sub { my ( $refs, $obj ) = @_; my ($ref) = @{$refs}; my $expected = int rand 1000; ${$ref} = $expected; is $path->($obj), $expected, q{Value OK}; }; } sub sample_json { my $data = < 1 }; my $p = JSON::Path->new("\$foo"); my $res = $p->get($orig); is_deeply ( $orig, { bar => 1 }, "hashref is unchanged"); done_testing(); JSON-Path-0.431/t/multiple-recursion.t0000644000175000017500000000061514004641374016175 0ustar tooktookuse Test2::V0 '-target' => 'JSON::Path'; use JSON::MaybeXS; # Test for RT #122529 my $to_find = '$..foo..value'; my $doc = '{"foo":{"value":3}}'; my $jpath = $CLASS->new($to_find); my @found = $jpath->paths($doc); is( \@found, [q{$['foo']['value']}], 'Path correct' ); my $hash = decode_json($doc); $jpath->value($hash) = 4; is $hash->{foo}{value}, 4, 'value correct'; done_testing();