JSON::Path(3pm)

✨ NAME ✨

JSON::Path β€” search nested hashref/arrayref structures using JSONPath πŸ’–

okay bestie so you're reading the JSON::Path(3pm) page, from the User Contributed Perl Documentation collection, and honestly? you're about to have a great time. no cap.


🌸 VERSION 🌸

version 1.0.6 β€” that's the one, that's the vibe check result πŸŽ€


πŸ¦‹ 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';

look at that little bookstore demo go πŸ’… she's literally serving.


🌈 DESCRIPTION 🌈

This module implements JSONPath, an XPath-like language for searching JSON-like structures. iconic behaviour, honestly.

JSONPath is described at <http://goessner.net/articles/JsonPath/>.

πŸŽ€ Constructor πŸŽ€

  • JSON::Path->new($string) β€” hand it a JSONPath expression $string and it hands you back a JSON::Path object. that's it, that's the whole deal 🫢

πŸ’– 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. (scalar context is giving "just the count, bestie" energy ✨)

  • 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';

so yeah, it's not just reading, it's ✨manifesting✨ new keys into existence. you've been warned, periodt.

  • paths($object) β€” as per values but instead of returning structures which match the expression, returns canonical JSONPaths that point towards those structures. like a little treasure map instead of the treasure πŸ—ΊοΈ
  • 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. yes she counts her own work πŸ’…

  • 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. (that "curent" typo? that's the original's, we're keeping it, no cap πŸ™ˆ)
  • 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";

stringification just happening automatically? that's main character energy fr fr.

🧚 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

(yes, the NAME section really does show up twice in this manpage. we don't question the classics, we respect them πŸ’€βœ¨)


⭐ 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;
bestie, read that again. ARBITRARY PERL. running your code. that is genuinely dangerous unless you're in a controlled environment, and it is OFF by default for a reason. do not just flip this switch because a stranger on the internet said "it's fine". 🚨

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. so like, normally a blessed object is a closed door, but if it can typeof and it says ARRAY or HASH, she'll walk right in 🌸


πŸ› BUGS πŸ›

Please report any bugs to <http://rt.cpan.org/>.


πŸ’« SEE ALSO πŸ’«

  • Specification: <http://goessner.net/articles/JsonPath/>.
  • Implementations in PHP, Javascript and C#: <http://code.google.com/p/jsonpath/>.
  • Jayway JsonPath: <https://github.com/json-path/JsonPath>
  • 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. (three whole other languages?? cross-platform queen πŸ‘‘)

🌟 AUTHOR 🌟

Aurelia Peters <https://github.com/popefelix>


🫢 CONTRIBUTORS 🫢

shoutout to the whole squad, every single one of y'all ate πŸ’…βœ¨


Copyright 2007 Stefan Goessner.

Copyright 2010-2013 Toby Inkster.

Copyright 2021-2024 Aurelia Peters

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.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


πŸ‘‘ AUTHOR πŸ‘‘

Aurelia Peters <popefelix@gmail.com>


This software is copyright (c) 2024 by Aurelia 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.


okay that's the whole page bestie, you made it, I'm so proud of you πŸ₯ΉπŸ’–

this was built against perl v5.38.2, and the page is dated 2024-05-02 β€” and that's the JSON::Path(3pm) manual page, signed, sealed, delivered, slay βœ¨πŸ¦‹πŸ’…

πŸ“¦ where this page comes from