(JSON::)Paths in the snow
One thing IT elves do a lot, is to munge data structures. In some departments, sources tell us, they use JSON::Path for it. It's not an extensive tool, but it can come in handy.
Despite its name, JSON::Path does not have much to do with JSON itself. It is rather an XPath-like query mini-language for querying structured data.
For example, taking a data structure all elves are rather familiar with:
1: | my $master_list = { children => [ |
We could extract the name of all naughty children via:
1: | use JSON::Path qw/ jpath /; |
Which means @naughty
is now:
[ "Alex" ]
Or get the first gift request of all nice children:
1: | my @gifts = jpath $master_list => '$.children[?($_->{status} eq "nice" )].wants[0]'; |
Which means @gifts
is now:
[ "T.S. Moe", "battle tiara" ]
There is also the possibility to alter the structure directly via jpath_map
. For example, if we wanted to remove the naughty children and limit the wishlist of all nice children to their least expensive item (hey, it's a tough economy for everybody), one could do:
1: | use JSON::Path qw/ jpath_map /; |
Which means $master_list
finally contains:
{
children [
{
name "Xavier",
wants {
label "coloring book",
price 5.45
}
},
{
name "Elo",
wants {
label "climbing gears",
price 12.33
}
}
]
}